gpt4 book ai didi

python - 如何根据其他两个列有条件地制作一个新的 pandas DF 列

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:52 26 4
gpt4 key购买 nike

我有一个如下所示的数据框:

col 1 | col2 | col3 | col4 | col5
'abc' | 1 | 20 | 10 | 15
'abc' | 2 | 25 | 5 | 30
'def' | 1 | 340 | 12 | 22
'def' | 2 | 185 | 16 | 120
...

我想创建另一个基于条件的列 col6:if col2 ==1, then col3 * col5,否则为0;如果 col2 == 2 then col4 * col5,否则为 0。因此生成的 df 应该如下所示:

col 1 | col2 | col3 | col4 | col5 | col6
'abc' | 1 | 20 | 10 | 15 | 300
'abc' | 2 | 25 | 5 | 30 | 150
'def' | 1 | 340 | 12 | 22 | 7480
'def' | 2 | 185 | 16 | 120 | 1920
...

如果 1 或 2 都没有,它应该返回 0 的原因是为了防止 col2 没有 1 或 2。

最佳答案

试试这个,

df.loc[df['col2'] ==1,'col6']=df['col3']*df['col5']
df.loc[df['col2'] ==2,'col6']=df['col4']*df['col5']
df['col6']=df['col6'].fillna(0)

关于python - 如何根据其他两个列有条件地制作一个新的 pandas DF 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50602820/

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