语法结构
DataFrame.apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwargs)
参数:
func:函数或 lambda 表达式,应用于每行或者每列
axis:{0 or ‘index’, 1 or ‘columns’}, 默认为0
0 or ‘index’: 表示函数处理的是每一列
1 or ‘columns’: 表示函数处理的是每一行
raw:bool 类型,默认为 False;
False ,表示把每一行或列作为 Series 传入函数中;
True,表示接受的是 ndarray 数据类型;
result_type:{‘expand’, ‘reduce’, ‘broadcast’, None}, default None
These only act when axis=1 (columns):
‘expand’ : 列表式的结果将被转化为列。
‘reduce’ : 如果可能的话,返回一个 Series,而不是展开类似列表的结果。这与 expand 相反。
‘broadcast’ : 结果将被广播到 DataFrame 的原始形状,原始索引和列将被保留。
args: func 的位置参数
**kwargs:要作为关键字参数传递给 func 的其他关键字参数,1.3.0 开始支持
返回值:
Series 或者 DataFrame:沿数据的给定轴应用 func 的结果
apply实战
import pandas as pd
import numpy as np
df = pd.DataFrame([[16, 1]] * 2, columns=['A', 'B'])
'''
A B
0 16 1
1 16 1
'''
df.apply(np.sqrt)
'''
A B
0 4 1
1 4 1
'''
df.apply(np.sum, axis=0)
'''
A 32
B 2
dtype: int64
'''
df.apply(lambda x: [1, 2], axis=1)
'''
0 [1, 2]
1 [1, 2]
2 [1, 2]
dtype: object
‘expand’ : 列表式的结果将被转化为列。
‘reduce’ : 如果可能的话,返回一个 Series,而不是展开类似列表的结果。这与 expand 相反。
‘broadcast’ : 结果将被广播到 DataFrame 的原始形状,原始索引和列将被保留。
args: func 的位置参数
'''
df.apply(lambda x: [1, 2], axis=1, result_type='expand')
'''
0 1
0 1 2
1 1 2
2 1 2
'''