如何在大 Pandas 分组之后从每个分组中选择前n行? - python

我有一个具有以下形状的熊猫数据框

 open_year, open_month, type, col1, col2, ....

我想找到每个(年,月)中的顶级类型,所以我首先找到每个(年,月)中的每种类型的数量

freq_df = df.groupby(['open_year','open_month','type']).size().reset_index()
freq_df.columns = ['open_year','open_month','type','count']

然后我想根据每个(year_month)的频率(例如计数)找到前n个类型。我怎样才能做到这一点?

我可以使用nlargest,但是我缺少类型

freq_df.groupby(['open_year','open_month'])['count'].nlargest(5)

但我缺少列type

参考方案

我建议您先按降序对计数进行排序,然后可以在GroupBy.head之后调用-

(freq_df.sort_values('count', ascending=False)
        .groupby(['open_year','open_month'], sort=False).head(5)
)

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

python :安装 python 后,如何导入 Pandas - python

我已经安装了 python 。现在,当我尝试跑步时import pandas as pd 我收到以下错误Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandasFile ImportError: …

python pandas:按行对条件进行分组 - python

我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…