1 回答
TA贡献1880条经验 获得超4个赞
申请之前的子集
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
添加回答
举报