如何根据条件用NaN替换数据框的列值?

7
例如,数据框的样子如下:
df = pd.DataFrame(
    [[1, 1], [2, 120], [3, 25], [4, np.NaN], [5, 45]],
    columns=["ID", "Age"])

在年龄列中,小于5和大于100的值必须转换为NaN。

你目前尝试了什么? - Courage
我正在尝试使用replace函数进行相同的操作,DF["Age"].replace(to_replace=DF["Age"]<5, value=np.NaN)。难道用replace函数不行吗? - Raja Sahe S
1个回答

14

使用wherebetween

df['Age'] = df.Age.where(df.Age.between(5, 100))
df
   ID   Age
0   1   NaN
1   2   NaN
2   3  25.0
3   4   NaN
4   5  45.0

使用.loc的另一种选择:

df.loc[df.Age.between(5, 100), 'Age'] = np.nan

非常感谢。使用replace函数或.loc有其他方法吗? - Raja Sahe S
1
@RajaSaheS 你可以检查一下 df.loc[df.Age.between(5,100),'Age']=np.nan - BENY
我终于找到了这个解决方案: DF["Age"].where((DF["Age"]>5) & (DF["Age"]<100) ,np.NaN,inplace=True) 感谢您的回复,帮助我解决了问题。 - Raja Sahe S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接