mac001
mac001

Reputation: 35

Python - Replace with null with 0 and check if less than

I am trying to check for nulls, replace them with zero and the check if the value is less than 5

From some research #df = df[df['speed'] < 5] will remove records that are greater than 5 and #df.fillna(0) will replace nulls

I have tried df = df[df[df['speed'].fillna(0, inplace=True)]< 5] however it returns an index error, I expect it needs to be done in steps

Thanks in advance

Upvotes: 1

Views: 2781

Answers (1)

jezrael
jezrael

Reputation: 863226

Use boolean indexing - with fillna without inplace=True, because inplace return None:

df[df['speed'].fillna(0) < 5]

Another solution:

df[(df['speed'] < 5) | df['speed'].isna()]

If need inplace operation use 2 steps, but NaNs are replaced by 0 in filtered DataFrame:

df['speed'].fillna(0, inplace=True)

df[df['speed'] < 5]

Upvotes: 2

Related Questions