Python apply関数

2504 ワード

Python apply関数
 
1、紹介
apply関数はpandas内のすべての関数の中で自由度が最も高い関数である.この関数は次のとおりです.
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
この関数が最も有用なのは最初のパラメータであり,このパラメータは関数であり,C/C++の関数ポインタに相当する.
この関数は自分で実現する必要があります.関数の伝達パラメータはaxisによって決まります.例えばaxis=1で、1行のデータをSeriesのデータ構造として自分の実現した関数に伝達します.私たちは関数の中でSeriesの異なる属性間の計算を実現し、1つの結果を返すと、apply関数は自動的に各行のDataFrameのデータを遍歴します.最後にすべての結果を1つのSeriesデータ構造に結合して返します.
2、サンプル
import numpy as np
import pandas as pd


f = lambda x: x.max()-x.min()

df = pd.DataFrame(np.random.randn(4,3),columns=list('bde'),index=['utah', 'ohio', 'texas', 'oregon'])
print(df)

t1 = df.apply(f)
print(t1)

t2 = df.apply(f, axis=1)
print(t2)

出力結果は次のとおりです.
               b         d         e
utah    1.106486  0.101113 -0.494279
ohio    0.955676 -1.889499  0.522151
texas   1.891144 -0.670588  0.106530
oregon -0.062372  0.991231  0.294464

b    1.953516
d    2.880730
e    1.016430
dtype: float64

utah      1.600766
ohio      2.845175
texas     2.561732
oregon    1.053603
dtype: float64

3、性能比較
df = pd.DataFrame({'a': np.random.randn(6),
                   'b': ['foo', 'bar'] * 3,
                   'c': np.random.randn(6)})


def my_test(a, b):
    return a + b


print(df)


df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) #   1
print(df)

df['Value2'] = df['a'] + df['c']  #   2
print(df)

出力結果は次のとおりです.
          a    b         c
0 -1.194841  foo  1.648214
1 -0.377554  bar  0.496678
2  1.524940  foo -1.245333
3 -0.248150  bar  1.526515
4  0.283395  foo  1.282233
5  0.117674  bar -0.094462

          a    b         c     Value
0 -1.194841  foo  1.648214  0.453374
1 -0.377554  bar  0.496678  0.119124
2  1.524940  foo -1.245333  0.279607
3 -0.248150  bar  1.526515  1.278365
4  0.283395  foo  1.282233  1.565628
5  0.117674  bar -0.094462  0.023212

          a    b         c     Value    Value2
0 -1.194841  foo  1.648214  0.453374  0.453374
1 -0.377554  bar  0.496678  0.119124  0.119124
2  1.524940  foo -1.245333  0.279607  0.279607
3 -0.248150  bar  1.526515  1.278365  1.278365
4  0.283395  foo  1.282233  1.565628  1.565628
5  0.117674  bar -0.094462  0.023212  0.023212

注意:データ量が多い場合は、簡単な論理処理について提案方法2(個人が数百Mデータセットを処理する場合、方法1に200 s程度、方法2に10 sかかる)!!!