将.apply()与1 df列一起使用

我在python / pandas中有一个带有多个列的df,并且想要做df.apply(some_function),将列的一个子集传递给'some_function'。

做这个的最好方式是什么?


白衣非少年
浏览 204回答 1
1回答

慕村225694

申请之前的子集In [151]: df = DataFrame(randn(10,3),columns=list('ABC'))In [152]: dfOut[152]:           A         B         C0 -0.071947 -0.243518 -0.1887821 -1.028449  0.525397  1.6290972  0.302620 -0.530769 -2.0392223  0.484875 -0.840589 -1.0065504  0.915714  0.631991  0.0442895 -1.444943 -0.603629  0.5528106 -0.113523  0.242165  1.3093737 -0.676176  2.827214  0.2236798 -0.467043  0.324336 -0.7042149  0.329897 -0.121696  1.810813In [153]: df[['A','B']].apply(sum)Out[153]: A   -1.768975B    2.210902dtype: float64In [154]: df[['A','B']].apply(lambda x: x.sum())Out[154]: A   -1.768975B    2.210902dtype: float64第二部分,按行应用,返回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]: dfOut[23]:      A    B     C0  foo  bar   bah1  foo  bar   bah2  foo  bar   bah3  foo  bar  bah24  foo  bar  bah2In [24]: df.apply(lambda x: x['A'] + x['B'] if x['C'] == 'bah' else x['A'] + x['C'],axis=1)Out[24]: 0     foobar1     foobar2     foobar3    foobah24    foobah2dtype: object
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python