python - 如何将唯一的行组合转换为排序的元组
问题描述
我有一个这样的数据框:
>>> df = pd.DataFrame([['bar',0],['restaurant',0],
... ['bar',0],
... ['movie',1],['bar',1],['restaurant',1],
... ['bar',2],['restaurant',2],['movie',2]]
... ,columns=['place','ID'])
>>> df
place ID
0 bar 0
1 restaurant 0
2 bar 0
3 movie 1
4 bar 1
5 restaurant 1
6 bar 2
7 restaurant 2
8 movie 2
我想按 ID 分组并按顺序获得地点的独特组合,并允许重复。如果我这样做:
>>> df.groupby('ID')['place'].unique().apply(lambda x: tuple(sorted(x))).reset_index()
ID place
0 0 (bar, restaurant)
1 1 (bar, movie, restaurant)
2 2 (bar, movie, restaurant)
这几乎是正确的,但我希望允许重复:
place ID
0 (bar, bar, restaurant) 0
1 (bar, movie, restaurant) 1
2 (bar, movie, restaurant) 2
非常感谢您的帮助。
解决方案
我会使用 groupby with as_index=False
without unique
。如果我们先订购而不是订购每个组,它也会更快。
new_df = (df.sort_values('place')
.groupby('ID',as_index=False)[['place']]
.agg(tuple))
print(new_df)
ID place
0 0 (bar, bar, restaurant)
1 1 (bar, movie, restaurant)
2 2 (bar, movie, restaurant)
或者 :
(df.sort_values('place')
.groupby('ID')['place']
.apply(tuple)
.reset_index()
)
推荐阅读
- python - 如何在python中使用opencv提取绿色通道?
- javascript - 如何使用 asp.net 和 SQL server 从数据库中填充 JavaScript 数组
- javascript - 如何修复 html2pdf.js 创建速度问题?
- selenium - 错误:程序类型已存在:org.openqa.selenium.WebDriver$Window
- xpath - XPath 和 JXPath 有什么区别?
- kubernetes - Openshift - 活性探针不适用于http
- node.js - 如何在 Node on Express 中的“putItem”期间向 DynamoDB 提供“支持的数据类型”
- r - 取数据框中每 3 列的行总和
- ios - UITableView 显示在状态栏下,我希望状态栏不透明,以便表格视图数据不会与状态栏重叠
- spring-mvc - 尝试加载引导模式元素时,Bean 名称的 BindingResult 和普通目标对象都不能用作请求属性