【发布时间】: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