1

I have a sample dataframe as below.

d={
    'Country' :['Bermuda','Australia','Switzerland','Norway','Iceland','United Kingdom','Denmark'],
    '1960':[231,3424,4354,857,644,2355,743],
    '1970':[8674,4364,564,7563,868,742,55],
    '1980':[44,5456,34556,34254,565,568,97],
    '1990':[23234,556,34,5656,67,89765,45],
    '2000':[343,6767,356,5657,324345,4566,346]
}

df=pd.DataFrame(d, columns=['Country','1960','1970','1980','1990','2000'])

It looks like this:

enter image description here

I want to show top-4 countries which have the highest values for each year as a result.

Expected results:

enter image description here

3 Answers 3

2

Another option using nlargest:

df.iloc[:,1:].apply(
    lambda col: df.Country.loc[col.nlargest(5).index].reset_index(drop=True)
)

#   1960            1970            1980            1990            2000
#0  Switzerland     Bermuda         Switzerland     United Kingdom  Iceland       
#1  Australia       Norway          Norway          Bermuda         Australia     
#2  United Kingdom  Australia       Australia       Norway          Norway        
#3  Norway          Iceland         United Kingdom  Australia       United Kingdom
#4  Denmark         United Kingdom  Iceland         Iceland         Switzerland   
Sign up to request clarification or add additional context in comments.

Comments

2

You can do the following:

temp={}

l=[i for i in df.columns if i!='Country']

for i in l:
    temp[i]=list(df.sort_values(by=i, ascending=False)['Country'].iloc[:4])

res=pd.DataFrame(temp)

>>> print(res)
             1960       1970            1980            1990            2000
0     Switzerland    Bermuda     Switzerland  United Kingdom         Iceland
1       Australia     Norway          Norway         Bermuda       Australia
2  United Kingdom  Australia       Australia          Norway          Norway
3          Norway    Iceland  United Kingdom       Australia  United Kingdom

Comments

1
>>> df.set_index('Country').apply(lambda col: col.nlargest(4).index)         

             1960       1970            1980            1990            2000
0     Switzerland    Bermuda     Switzerland  United Kingdom         Iceland
1       Australia     Norway          Norway         Bermuda       Australia
2  United Kingdom  Australia       Australia          Norway          Norway
3          Norway    Iceland  United Kingdom       Australia  United Kingdom

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.