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?
CodePudding user response:
You can use mask which replaces values where the condition is True with a value (the default is NaN):
out = k.mask(k>5)
Output:
A B
0 1 3.0
1 2 4.0
2 3 5.0
3 4 NaN
4 5 NaN
CodePudding user response:
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])
