Pandas DataFrame - assign 1,0 values based on other column

Viewed 3524

I've got a dataframe containing country names & their percentage of energy output. I need to add a new column that assigns a 1 or 0, based on whether the country's energy output is above or below the median of energy output. Some dummy code is:

import pandas as pd
def answer():
    df = pd.DataFrame({'name':['china', 'america', 'canada'], 'output': [33.2, 15.0, 5.0]})
    df['newcol'] = df.where(df['output'] > df['output'].median(), 1, 0)
    return df['newcol']
answer()

the code returns

ValueError: Wrong number of items passed 2, placement implies 1

I feel like this is an incredibly simple fix but I'm new to working with Pandas. Please help end my frustration

2 Answers
Related