1

python/pandas にいくつかの列を持つ df があり、列のサブセットを 'some_function' に渡す df.apply(some_function) を実行したいと考えています。

これを行う最善の方法は何ですか?

前もって感謝します!

4

1 に答える 1

6

申し込む前にサブセット化

In [151]: df = DataFrame(randn(10,3),columns=list('ABC'))

In [152]: df
Out[152]: 
          A         B         C
0 -0.071947 -0.243518 -0.188782
1 -1.028449  0.525397  1.629097
2  0.302620 -0.530769 -2.039222
3  0.484875 -0.840589 -1.006550
4  0.915714  0.631991  0.044289
5 -1.444943 -0.603629  0.552810
6 -0.113523  0.242165  1.309373
7 -0.676176  2.827214  0.223679
8 -0.467043  0.324336 -0.704214
9  0.329897 -0.121696  1.810813

In [153]: df[['A','B']].apply(sum)
Out[153]: 
A   -1.768975
B    2.210902
dtype: float64

In [154]: df[['A','B']].apply(lambda x: x.sum())
Out[154]: 
A   -1.768975
B    2.210902
dtype: float64

2 番目の部分は、行単位で適用され、A 列と B 列の要素の「合計」を返します。必要なものはほとんど適用できます。

In [21]: df = DataFrame(dict(A = 'foo', B = 'bar', C = 'bah'),index=range(5))

In [22]: df.loc[[3,4],'C'] = 'bah2'

In [23]: df
Out[23]: 
     A    B     C
0  foo  bar   bah
1  foo  bar   bah
2  foo  bar   bah
3  foo  bar  bah2
4  foo  bar  bah2

In [24]: df.apply(lambda x: x['A'] + x['B'] if x['C'] == 'bah' else x['A'] + x['C'],axis=1)
Out[24]: 
0     foobar
1     foobar
2     foobar
3    foobah2
4    foobah2
dtype: object
于 2013-06-27T13:57:43.703 に答える