我尝试根据同一数据框中另一个系列的缺失值来选择熊猫系列的部分。
我使用了.loc
,这是一个很好的解决方案。
df.loc[df["B"].isnull(), "A"] = np.NaN
我最初想使用:
df["A"].replace(df["B"].isnull(), np.NaN, inplace=True)
这不起作用。为什么会这样?
答案 0 :(得分:4)
replace
用于替换特定值-不适用于布尔掩码。如果要遮罩元素,则要使用的正确函数将是Series.where
或mask
。
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