gpt4 book ai didi

Python pandas 适用于更多列

转载 作者:太空宇宙 更新时间:2023-11-04 05:54:55 24 4
gpt4 key购买 nike

如何使用 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)

关于Python pandas 适用于更多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28327126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com