一、介绍数据结构
apply函数是pandas里面全部函数中自由度最高的函数。该函数以下:app
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)dom
该函数最有用的是第一个参数,这个参数是函数,至关于C/C++的函数指针。函数
这个函数须要本身实现,函数的传入参数根据axis来定,好比axis = 1,就会把一行数据做为Series的数据 结构传入给本身实现的函数中,咱们在函数中实现对Series不一样属性之间的计算,返回一个结果,则apply函数 会自动遍历每一行DataFrame的数据,最后将全部结果组合成一个Series数据结构并返回。性能
二、样例spa
import numpy as np import pandas as pd if __name__ == '__main__': f = lambda x : x.max() - x.min() df = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) #columns表述列标, index表述行标 print(df) t1 = df.apply(f) #df.apply(function, axis=0),默认axis=0,表示将一列数据做为Series的数据结构传入给定的function中 print(t1) t2 = df.apply(f, axis=1) print(t2)
输出结果以下所示:.net
b d e utah 1.950737 0.318299 0.387724 ohio 1.584464 -0.082965 0.984757 texas 0.477283 -2.774454 -0.532181 oregon -0.851359 -0.654882 1.026698
b 2.802096 d 3.092753 e 1.558879 dtype: float64
utah 1.632438 ohio 1.667428 texas 3.251737 oregon 1.878057 dtype: float64
三、性能比较指针
import numpy as np import pandas as pd def my_test(a, b): return a + b if __name__ == '__main__': df = pd.DataFrame({'a':np.random.randn(6), 'b':['foo', 'bar'] * 3, 'c':np.random.randn(6)}) print(df) df['value1'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) print(df) df['vaule2'] = df['a'] + df['c'] print(df)
输出结果以下:code
a b c 0 -1.745471 foo 0.723341 1 -0.378998 bar 0.229188 2 -1.468866 foo 0.788046 3 -1.323347 bar 0.323051 4 -1.894372 foo 2.216768 5 -0.649059 bar 0.858149
a b c value1 0 -1.745471 foo 0.723341 -1.022130 1 -0.378998 bar 0.229188 -0.149810 2 -1.468866 foo 0.788046 -0.680820 3 -1.323347 bar 0.323051 -1.000296 4 -1.894372 foo 2.216768 0.322396 5 -0.649059 bar 0.858149 0.209089
a b c value1 vaule2 0 -1.745471 foo 0.723341 -1.022130 -1.022130 1 -0.378998 bar 0.229188 -0.149810 -0.149810 2 -1.468866 foo 0.788046 -0.680820 -0.680820 3 -1.323347 bar 0.323051 -1.000296 -1.000296 4 -1.894372 foo 2.216768 0.322396 0.322396 5 -0.649059 bar 0.858149 0.209089 0.209089
注意:当数据量很大时,对于简单的逻辑处理建议方法2(我的处理几百M数据集时,方法1花时200s左右,方法2花时10s)!!!blog