python-3.x - Pandas 中的 SQL 选择和分组依据
问题描述
Track Actor Movie
1 Katherine Hepburn Guess Who's Coming to Dinner
2 Katherine Hepburn Guess Who's Coming to Dinner
3 Katherine Hepburn On Golden Pond
4 Katherine Hepburn The Lion in Winter
5 Bette Davis What Ever Happened to Baby Jane?
6 Bette Davis The Letter
7 Bette Davis The Letter
...
100 Omar Shariff Lawrence of Arabia
需要在 python 中编写代码来选择所有出演过不止一部电影的演员并将他们的名字附加到一个列表中。
以下 SQL 查询的 python 等效项。
SELECT Actor, count(DISTINCT Movie)
FROM table
GROUP by Actor
HAVING count(DISTINCT Movie) > 1
解决方案
您可以对电影值使用drop_duplicates()
方法:DISTINCT
df=df.drop_duplicates(subset=['Actor','Movie'])
现在对于分组和聚合使用groupby()
方法和链agg()
方法:
result=df.groupby('Actor').agg(count=('Movie','count'))
最后使用布尔掩码并检查您的条件(计数> 1):
result=result[result['count']>1]
推荐阅读
- python - 如何在列表中的每个元素之后插入新行?Python
- java - WebDriverWait depreciated 不再适用于隐式等待
- sql-server - 访问列表框查询阻止 SQL Server 更新查询
- spring-boot - 将 Spring JPA 存储库专门用于测试
- node.js - 为什么测试脚本一直无法完成测试脚本执行?JEST nodejs 测试超时错误
- postgresql - 如何从 docker 中删除所有 postgresql 数据,包括创建的用户和数据库?
- r - 如何获取矢量并将其复制粘贴到我的 R 代码中,就像我手动输入它一样?
- postgresql - 有没有办法测量 PostgreSQL 实例中的日志量?
- java - 分配新变量(setter)并调用repaint()后无法更改paintComponent的输出
- android - 如何在 AWS pinpoint 中创建可由 Android Kotlin 中的 OnClick 事件触发的事件