【发布时间】:2015-02-04 17:00:14
【问题描述】:
如何使用 apply 和更多列在数据框中生成更多列?我的 df 是:
A B C
0 11 21 31
1 12 22 31
如果我只想生成一个完美运行的列:
df['new_1']=df[['A','C','B']].apply(lambda x: x[1]/2, axis=1)
结果是:
A B C new_1
0 11 21 31 15.5
1 12 22 32 16.0
但是,如果我想生成多个列怎么办? 这非常有效:
df[['new_1','new_2']]=df[['A','C']].apply(lambda x: [x[1]/2,x[1]*2], axis=1)
结果是:
A B C new_1 new_2
0 11 21 31 15.5 62
1 12 22 32 16.0 64
但是如果我想在 apply 中使用多于两列呢?
df[['new_1','new_2']]=df[['A','B','C']].apply(lambda x: [x[1]/2,x[2]*2], axis=1)
我收到此错误:
KeyError: "['new_1' 'new_2'] not in index"
有什么帮助吗?我使用 Python 2.7 和 pandas 0.15.2
谢谢!
【问题讨论】:
标签: python pandas dataframe apply