Create a new column with 1 if the country's % Renewable is above median else 0

Viewed 350

There is a column called country's '% Renewable'. I want to create a column consisting of 1 if the value in the column is above the median value of the column and 0 if it is below the median value. Here is my code

def answer_ten():
    Top15 = answer_one()
    avg=Top15['% Renewable'].median(axis=0)
    print(avg)
    #print(Top15['% Renewable'])
    for value in Top15['% Renewable']:
        if(value>=avg):
            Top15['HighRenew']=1
        else:
            Top15['HighRenew']=0
    print(Top15[['HighRenew','% Renewable']])
    Top15['HighRenew']=Top15['HighRenew'].sort_values(ascending = False)       

answer_ten()

But the output I got is :

14.96908
                    HighRenew  % Renewable
Country                                   
Australia                   0    11.810810
Brazil                      0    69.648030
Canada                      0    61.945430
China                       0     0.000000
France                      0    17.020280
Germany                     0    17.901530
India                       0    14.969080
Iran                        0     5.707721
Italy                       0    33.667230
Japan                       0    10.232820
Russian Federation          0    17.288680
South Korea                 0     2.279353
Spain                       0    37.968590
United Kingdom              0    10.600470
United States               0    11.570980

The avg value is 14.96908. Thanx in advance.

1 Answers

IIUC use,

(df['% Renewable'].gt(df['% Renewable'].median())).astype(int)

Output:

country
Australia             0
Brazil                1
Canada                1
China                 0
France                1
Germany               1
India                 0
Iran                  0
Italy                 1
Japan                 0
Russian Federation    1
South Korea           0
Spain                 1
United Kingdom        0
United States         0
Name: % Renewable, dtype: int64
Related