首页 > 解决方案 > 你如何在 Python Pandas 中进行分组、排序和限制?(即获得前 10 名)

问题描述

我有一个包含 actor_id 和 account_id 列的 Pandas 数据框。演员是一个人,而帐户只是一个帐户。所以一个人可以有多个账户,账户可以有多个人。

我的目标是按 actor_id 分组,然后按他们拥有的帐户数量对 actor_ids 进行排名,这样我就可以获得帐户最多的前 10 名演员的列表。

在 SQL 中,它类似于 SELECT actor_id, account_id, COUNT(account_id) GROUP BY actor_id LIMIT 10。但我正在尝试在 Python 中执行此操作。

我引用了这个Pandas 组并按索引计数排序,但它对我不起作用。下面是我尝试过的代码。

df['count'] = df['actor_id'].map(df['account_id'].value_counts())
df.sort_index('count', ascending=False)

数据集如下所示: 数据集

在图片中,将 project_id 替换为 account_id。

标签: pythonpandaspandas-groupby

解决方案


你可以做:

df_nb_acc = (
    df.groupby('actor_id')['account_id'] #groupby actor_id, select the column account_id
      .count() # count the number of accout per actor
      .reset_index() # actor_id become a column and not indexes 
      .rename(columns={'account_id':'Nb_account'}) # to rename the column
      .sort_values('Nb_account',axis=1, ascending=False)
      # to sort the value on the column Nb_account, largest to smallest
    )

并获得前 10 名然后做df_nb_acc.head(10)


推荐阅读