python - 你如何在 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。
解决方案
你可以做:
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)
推荐阅读
- extjs - 是否可以在 Ext.data.Model 上映射一对多关系
- batch-file - 使用用户输入控制函数调用:批处理
- javascript - 渲染编码的 HTML 字符
- homebrew - zsh compinit:安装 Homebrew 后 Mac 上的不安全目录错误消息
- sql-server - 如何重写 MDX 语句,因此将基于 LastNonEmpty 措施(表示随时间变化的版本)
- python - 无法在 python 中关闭 SSH 连接
- python - 如何使用 Pyserial 发送和接收数据?
- javascript - 动态 key 与 value 成 object 成 react
- excel - 自定义转置数据
- oauth-2.0 - SharePoint Online 获取身份验证令牌而不重定向到 URL