DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), by_row=‘compat’, kwargs)
沿df的轴应用函数
>>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
>>> df
A B
0 4 9
1 4 9
2 4 9
>>> df.apply(np.sqrt)
A B
0 2.0 3.0
1 2.0 3.0
2 2.0 3.0
# 按照列
>>> df.apply(np.sum, axis=0)
A 12
B 27
dtype: int64
# 按照行
>>> df.apply(np.sum, axis=1)
0 13
1 13
2 13
dtype: int64
# 在Series中返回list
df.apply(lambda x: [1, 2, 3], axis=1)
0 [1, 2, 3]
1 [1, 2, 3]
2 [1, 2, 3]
dtype: object
df.apply(lambda x: [1, 2, 3], axis=1, result_type='expand')
0 1 2
0 1 2 3
1 1 2 3
2 1 2 3