首页 > 解决方案 > 如何将唯一的行组合转换为排序的元组

问题描述

我有一个这样的数据框:

>>> 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

非常感谢您的帮助。

标签: pythonpandaspandas-groupby

解决方案


我会使用 groupby with as_index=Falsewithout 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()
)

推荐阅读