Skip to main content
 首页 » 编程设计

python之将 .apply() 与超过 1 个 df 列一起使用

2025年05月04日31sxdcgaq8080

我在 python/pandas 中有一个包含多个列的 df,我想执行 df.apply(some_function) 将列的子集传递给“some_function”。

执行此操作的最佳方法是什么?

提前致谢!

请您参考如下方法:

申请前的子集

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 

第二部分,按行应用,返回 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