orie
orie

Reputation: 571

Turn NaN in dataframe if condition met

I have a column here that looks like this and is part of a dataframe:

df.Days_Since_Earnings
Out[5]: 
0      21.0
2       1.0
4    1000.0
5     500.0
6     119.0
Name: Days_Since_Earnings, Length: 76, dtype: float64

I want to leave it as it is except I want to turn numbers above 120 to 'nan's, so it would look like this:

df.Days_Since_Earnings
Out[5]: 
0      21.0
2       1.0
4       nan
5       nan
6     119.0
Name: Days_Since_Earnings, Length: 76, dtype: float64

thanks to anyone who helps!

Upvotes: 1

Views: 1896

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

You can use mask:

df['Days_Since_Earnings'] = df.Days_Since_Earnings.mask(df.Days_Since_Earnings > 120)

or where with reverse condition

df['Days_Since_Earnings'] = df.Days_Since_Earnings.where(df.Days_Since_Earnings <= 120)

or loc assignment:

df.loc[df.Days_Since_Earnings > 120, 'Days_Since_Earnings'] = np.nan

Upvotes: 2

NYC Coder
NYC Coder

Reputation: 7594

df['days'] = df['days'].apply(lambda x: np.nan if x > 120 else x)
print(df)

Or

df[df['days'] > 120] = np.nan

    days
0   21.0
1    1.0
2    NaN
3    NaN
4  119.0

Upvotes: 1

Related Questions