在熊猫中将`替换`与`isnull`组合在一起

时间:2019-06-27 14:31:39

标签: python pandas

我尝试根据同一数据框中另一个系列的缺失值来选择熊猫系列的部分。

我使用了.loc,这是一个很好的解决方案。

df.loc[df["B"].isnull(), "A"] = np.NaN

我最初想使用:

df["A"].replace(df["B"].isnull(), np.NaN, inplace=True)

这不起作用。为什么会这样?

1 个答案:

答案 0 :(得分:4)

replace用于替换特定值-不适用于布尔掩码。如果要遮罩元素,则要使用的正确函数将是Series.wheremask

df['A'].where(~df['B'].isnull(), np.NaN, inplace=True)
# or, more simply,
df['A'].where(~df['B'].isnull(), inplace=True)
# or,
df['A'].mask(df['B'].isnull(), inplace=True)

最小可验证示例

df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [np.nan, 1, np.nan], })
df
   A    B
0  a  NaN
1  b  1.0
2  c  NaN

# df['A'].where(~df['B'].isnull(), inplace=True)
df['A'].mask(df['B'].isnull(), inplace=True)
df
     A    B
0  NaN  NaN
1    b  1.0
2  NaN  NaN