9

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 convert to NaN.

2
  • what have you tried so far? Commented Dec 31, 2018 at 4:29
  • I am trying out the same with replace function, DF["Age"].replace(to_replace=DF["Age"]<5, value=np.NaN) Is that not possible to do with replace ? Commented Dec 31, 2018 at 4:42

1 Answer 1

16

Using where and between:

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

Another option using .loc:

df.loc[df.Age.between(5, 100), 'Age'] = np.nan
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.