1

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 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.