从pandas.DataFrame的每列中获取最大值

Mic*_*ael 9 python dataframe pandas

这是我的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'])
Run Code Online (Sandbox Code Playgroud)

我想创建一个新的DataFrame,它将包含我的每一列的前三个值data DataFrame.

这是预期的输出:

   first  second  third
0     89      76     98
1     56      45     87
2     40      45     67
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Zel*_*ny7 9

创建一个函数来返回系列的前三个值:

def sorted(s, num):
    tmp = s.sort_values(ascending=False)[:num]  # earlier s.order(..)
    tmp.index = range(num)
    return tmp
Run Code Online (Sandbox Code Playgroud)

将其应用于您的数据集:

In [1]: data.apply(lambda x: sorted(x, 3))
Out[1]:
   first  second  third
0     89      76     98
1     56      45     87
2     40      45     67
Run Code Online (Sandbox Code Playgroud)