gpt4 book ai didi

python - Pandas :根据其他列和值本身更改单元格值

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:47 32 4
gpt4 key购买 nike

我有以下 Pandas df:

category1   category2
A B
A C
B NaN
A NaN

如果满足以下条件,我想将 category2 中的值更改为 D:

  • 类别 1 == A
  • category2 == NaN

因此我的预期输出是:

category1   category2
A B
A C
B NaN
A D

我尝试了两种方式:

df.loc[((df.category1 == "A") & (df.category2 == 'nan')), "category2"] = "D" # doesn't change anything

import numpy as np
df['category2'] = np.where(((df['category1'] == 'A') & (df['category2'] == "")), "D")
# ValueError: either both or neither of x and y should be given

为什么两条线都不起作用?

最佳答案

使用以下内容:

df.loc[df.category2.isna()&df.category1.eq('A'),'category2']='D'
print(df)

  category1 category2
0 A B
1 A C
2 B NaN
3 A D

关于python - Pandas :根据其他列和值本身更改单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171941/

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