Python- To fill values with NaN if they are in a specific range of values

Issue

I am working on a requirement where I have to fill specific values as NaN if they fall in a particular range of no’s.
Below is my code-

import pandas as pd
data = {'A': [1, 2,3,4,5], 'B': [3, 4,5,6,7]}
k=pd.DataFrame(data)

If no’s are greater than 5, then fill those specific values in the column as NaN.

So col B would be like 'B':[3,4,5,NaN,NaN]

How would I do it?

Solution

You can use np.where condition here which follows a simple structure of np.where(condition/s, True Value, False Value) . np.where follows basic broadcasting rules, hence if don’t want to provide an else condition then you could simply pass the column in False Value.

If you would like to do for only column B:

k['B'] = np.where(k['B'] > 3, np.NaN, k['B'])

If you want to perform for the whole DataFrame :

for col in k.columns:
    k[col] = np.where(k[col] > 3, np.NaN, k[col])

Answered By – Navneet Kumar

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.