Skip to main content
 首页 » 编程设计

Python pandas 适用于更多列

2025年05月04日8开发

如何使用 apply with more columns 在数据框中生成更多列?我的 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 

但是如果我想在申请时使用两个以上的列怎么办?

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

谢谢!

请您参考如下方法:

在 apply 中使用 Series 构造函数通常可以达到目的:

In [11]: df[['new_1','new_2']] = df[['A','B','C']].apply(lambda x: pd.Series([x[1]/2,x[2]*2]), axis=1) 
 
In [12]: df 
Out[12]: 
    A   B   C  new_1  new_2 
0  11  21  31     10     62 
1  12  22  31     11     62 

没有它我看到了一个不同的错误(赋值前):

In [21]: df[['A','B','C']].apply(lambda x: [x[1]/2,x[2]*2], axis=1) 
ValueError: Shape of passed values is (2, 2), indices imply (2, 3)