1

This is my dataframe. I want to create a new column named mpg_high

enter image description here

The condition of the column is: mpg_high = 1 if mpg > average mpg (this is the mean of mpg where I placed np.mean(df.mpg) else = 0.

I tried various methods but kept getting syntax errors. How can I do this?

Thanks in advance

2 Answers 2

1

You can use np.where:

df['mpg_high'] = np.where(df.mpg > np.mean(df.mpg), 1, 0)
Sign up to request clarification or add additional context in comments.

Comments

1

It can be reduced to straight binary comparison and conversion to int

df = pd.DataFrame({"mgp":np.random.randint(15,35, 50)})

df["mgp_high"] = df["mgp"].gt(df["mgp"].mean()).astype(int)

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.