Pandas Dataframe - replace value with boolean mask

Viewed 119

I have a dataframe with a column named 'Temperature'

data = {'Day':  [1,2,3,4],
        'Temperature': [20,30,40,50]
        }

Now, I don't want the temperature digit but to assign '1' to the cell where Temperature is within the range of 25 to 45. If it is not, I will assign 0 to it.

My desired dataframe is

    data = {'Day':  [1,2,3,4],
        'Temperature': [0,1,1,0]
        }

I have a boolean mask like below:

df[(df['Temperature']<=45) & (df['Temperature']>=25)]

How to use Boolean mask to achieve this? Or, What is the best way to do this?

Thank you.

2 Answers

Idea is convert boolean mask to 0,1 by cast to integers:

df = pd.DataFrame(data)

df['Temperature'] = ((df['Temperature']<=45) & (df['Temperature']>=25)).astype(int)

df['Temperature'] = np.where(df['Temperature']<=45) & (df['Temperature']>=25), 1, 0)

Similar solution with Series.between:

df['Temperature'] = df['Temperature'].between(25, 45).astype(int)

df['Temperature'] = np.where(df['Temperature'].between(25, 45), 1, 0)
data = {'Day':  [1,2,3,4],
        'Temperature': [20,30,40,50]
        }

df = pd.DataFrame(data)
df[(df['Temperature']<=45) & (df['Temperature']>=25)] = 1
df[(df['Temperature']>=45) & (df['Temperature']>=25)] = 0
Related