慕村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