我有以下熊猫df:

category1   category2
A           B
A           C
B           NaN
A           NaN


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


category1 == 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

08-19 21:43