【问题标题】:How to get field which has fifth in the order of the highest value in pandas如何获取熊猫中按最高值排序的第五个字段
【发布时间】:2018-12-10 23:17:24
【问题描述】:

我正在使用 pandas,我有这样的数据集:

**ID name total-cost**
  1  a    7
  2  b    4
  3  c    1
  4  e    6
  5  f    80
  6  k    85

所以我需要按总成本最高的顺序获得第五个值,这里是 4 [85 80 7 6 4 1]。不是名称,不是 ID,只是一个值。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以排序,然后使用iloc 得到第五个值:

    df.sort_values('total-cost', ascending=False)['total-cost'].iloc[4]
    

    或者使用nlargest(5)得到最大的5个,然后使用iloc得到最后一个值:

    df['total-cost'].nlargest(5).iloc[-1]
    

    【讨论】:

    • Series.nlargest根据文档按排序顺序返回。
    • 感谢 ALollz,我略读了那部分。所以它应该工作
    • 您也可以使用pd.Series.rank 进行更精细的控制。
    • 如果我想得到前 5 个值的数组,像这样:[85 80 7 6 4],我该怎么做呢?我试过这个stackoverflow.com/questions/39867061/…,但这对我没有帮助。对不起,如果我很无聊,我是熊猫的新手。 ://
    • df['total-cost'].nlargest(5).values
    【解决方案2】:

    你可以使用函数nlargest(n)来得到n个最大的数,如下所示

    import pandas as pd
    df = pd.DataFrame([['a',7],['b',4],['c',1],['e',6],['f',80],['k',85]], columns=['name','total_cost'])
    In [2]: df.total_cost.nlargest(5)
    Out[2]: 
    5    85
    4    80
    0     7
    3     6
    1     4
    Name: total_cost, dtype: int64
    

    df.nlargest(n) 返回具有原始索引和 n 个最大值的 pandas Series

    如果您只需要第 5 个最大值,您可以使用df.total_cost.nlargest(5).reset_index().total_cost[4]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-28
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2018-06-10
      • 2019-06-03
      相关资源
      最近更新 更多