Pandas可以使用apply将函数作用到DataFrame某个轴,用applymap将一个规则应用到DataFrame中的每个元素,用map将一个规则应用到某一列。
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.arange(12).reshape(4,3), columns=list("bde"), index=['one', 'two', 'three', 'four'])
# b d e
# one 0 1 2
# two 3 4 5
# three 6 7 8
# four 9 10 11
f = lambda x:x.max()-x.min()
frame.apply(f) # 列上应用f
# b 9
# d 9
# e 9
# dtype: int64
frame.apply(f, axis=1) # 行上应用f
# one 2
# two 2
# three 2
# four 2
# dtype: int64
f1 = lambda num: "%.2f" % num
# 应用于每个元素
frame1 = frame.applymap(f1)
frame1
# b d e
# one 0.00 1.00 2.00
# two 3.00 4.00 5.00
# three 6.00 7.00 8.00
# four 9.00 10.00 11.00
# 应用于到某一列
frame['d'].map(lambda x: x+10)
# one 11
# two 14
# three 17
# four 20
# Name: d, dtype: int64