Numpy的ufuncs(元素级的数组方法)可用于操作pandas对象
frame = DataFrame(np.random.randn(4, 3), columns=list('bde'),
index=['Utah', 'Ohio', 'Texas', 'Oregon'])
np.abs(frame)
将函数应用到各行各列组成的一维数组中
f = lambda x: x.max() - x.min()
frame.apply(f)
b 1.802165
d 1.684034
e 2.689627
dtype: float64
应用到列上
frame.apply(f, axis=1)
Utah 0.998382
Ohio 2.521511
Texas 0.676115
Oregon 2.542656
dtype: float64
许多常见的数组统计功能都被实现成DataFrame的方法,因此无需使用apply。
传递给apply的函数也可以返回由多个值组成的Series
def f(x):
return Series([x.min(), x.max()], index=['min', 'max'])
frame.apply(f)
b d e
min -0.555730 0.281746 -1.296221
max 1.246435 1.965781 1.393406
假设希望对frame中的各个浮点值格式化字符串,可以使用applymap
format = lambda x: '%.2f' % x
frame.applymap(format)
b d e
Utah -0.20 0.48 -0.52
Ohio -0.56 1.97 1.39
Texas 0.09 0.28 0.77
Oregon 1.25 1.01 -1.30
Series有一个引用元素级函数的map方法
frame['e'].map(format)