How to replace a dataframe column values with NaN based on a condition?

坚强是说给别人听的谎言 提交于 2021-02-07 09:53:45

问题


For example, The dataframe looks like:

DF=pd.DataFrame([[1,1],[2,120],[3,25],[4,np.NaN],[5,45]],columns=["ID","Age"])

In the Age column, the values below 5 and greater than 100 have to converted to NaN.

Any help is appreciated!


回答1:


Using where and between

df.Age=df.Age.where(df.Age.between(5,100))
df
   ID   Age
0  10   NaN
1  20   NaN
2  30  25.0


来源:https://stackoverflow.com/questions/53983563/how-to-replace-a-dataframe-column-values-with-nan-based-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!