【问题标题】:Top 10 Rank for Each Company for Each Month各公司每月前10名
【发布时间】:2019-01-30 11:06:55
【问题描述】:

我有一个数据集,它使用 groupby 按年、月、msa 和公司汇总 pmt_unit 的数量。

我希望每个月都能获得每家公司的 pmt_units 最多的前 10 名。

这是用于获取完整排名列表的代码:

#For each month for each builder, provide the pmt_units for the top ten cities 
#Group by Month and MSA
SFU_grouped = SFU_2.groupby(['uyear','umonth','msa','stock_ticker']).agg({'pmt_units': 'sum'}).reset_index()

按时间顺序排序,然后按公司和按 pmt_units 从高到低排列 MSA。为每家公司添加一个按 pmt_unit 对 msa 进行排名的列

SFU_ordered=SFU_grouped.sort_values(['uyear','umonth','company','pmt_units'],
ascending =[True, True, True, False])
SFU_ordered['city_rank']=SFU_ordered.groupby(['company','umonth','uyear'])['pmt_units'].rank(method = 'dense', ascending = False).astype(int)

我试过了

SFU_ordered.groupby('company').apply(lambda x: x.nlargest(10,'pmt_units')).reset_index(drop=True)

但这只是给了我每家公司有史以来前十个最好的最高许可月份。

我怎样才能按月获得每家公司的前 10 名坦克?

编辑:我已在此处阐明了 MSA 的角色。这是一个示例表:

Image of Sample Table enter image description here

编辑:我通过传递解决了我的问题:

SFU_year_rank = SFU_year_ordered.set_index('msa').groupby('company')['pmt_units'].nlargest(10).reset_index()

【问题讨论】:

  • 您可以发布您的 DataFrame 示例吗?
  • 我尝试发布 ASCII 示例表,但无法正确格式化。会继续努力。

标签: pandas pandas-groupby rank


【解决方案1】:

试试这个:

SFU_ordered['city_rank']=SFU_ordered.groupby(['umonth','company','uyear'])['pmt_units'].rank(method = 'dense', ascending = False).astype(int)

【讨论】:

  • 谢谢。这给了我完整的排名。我只是希望每个公司每个月都能进入前 10 名。正在尝试上传示例以供参考。
【解决方案2】:

你试过了吗

    top_n = 10
    top_ten_cities = (SFU_ordered
        .groupby(['umonth','company','uyear'])['pmt_units']
        .apply(lambda x: x.sort_values(ascending=False).head(top_n))

head(n) 返回系列的前 n 行

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多