Python Pandas replace values if not in value range


I would like to replace all cells of a column if each value IS NOT in a specific value range.

E.g. value range between 0 and 10

The function should put np.NaN on all cells which are below 0 or above 10.

I tried with this:

df.loc[(df["B"] < 5 ), "B"] = np.NaN

but it only works with a specific value, not with a value range.

Is there a simple solution to replace all values outside a specific value range, without iterating through all rows?


I will choose between func

df.loc[~df.B.between(0, 10), "B"] = np.nan

Answered By – 辜乘风

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.