Get top biggest values from each column of the pandas.DataFrame

Viewed 8826

Here is my pandas.DataFrame:

import pandas as pd
data = pd.DataFrame({
  'first': [40, 32, 56, 12, 89],
  'second': [13, 45, 76, 19, 45],
  'third': [98, 56, 87, 12, 67]
}, index = ['first', 'second', 'third', 'fourth', 'fifth'])

I want to create a new DataFrame that will contain top 3 values from each column of my data DataFrame.

Here is an expected output:

   first  second  third
0     89      76     98
1     56      45     87
2     40      45     67

How can I do that?

5 Answers

Alternative pandas solution:

In [6]: N = 3

In [7]: pd.DataFrame([df[c].nlargest(N).values.tolist() for c in df.columns],
   ...:              index=df.columns,
   ...:              columns=['{}_largest'.format(i) for i in range(1, N+1)]).T
   ...:
Out[7]:
           first  second  third
1_largest     89      76     98
2_largest     56      45     87
3_largest     40      45     67

Use nlargest like

In [1594]: pd.DataFrame({c: data[c].nlargest(3).values for c in data})
Out[1594]:
   first  second  third
0     89      76     98
1     56      45     87
2     40      45     67

where

In [1603]: data
Out[1603]:
        first  second  third
first      40      13     98
second     32      45     56
third      56      76     87
fourth     12      19     12
fifth      89      45     67
Related