首页 > 解决方案 > 数据框按值分组,删除重复项,但保存不相似的条目?Python

问题描述

有没有办法在python中扫描数据框以创建一个按特定列分组的新数据框,删除重复项,同时保存不相似的条目,比如放入列表中?

所以如果我有一个看起来像这样的数据框......

Genre     Rating   CustomRating
Thriller  5        5
Thriller  5        5
Comedy    9        9
Action    3        6
Action    2        7

我需要它变成这样的东西......

Genre     Rating   CustomRating
Thriller  5        5
Comedy    9        9
Action    3, 2     6, 7

进度更新

@ignoring_gravity 建议工作做得df.drop_duplicates().groupby('Genre', sort=False).agg(list)很好,但是有没有办法将项目返回为字符串或 int 而不是列表?

标签: pythonpandasdataframe

解决方案


你可以这样做groupby,然后agg

df.groupby('Genre', sort=False).agg(lambda x: list(set(x))).reset_index()

你会得到

      Genre  Rating CustomRating
0  Thriller     [5]          [5]
1    Comedy     [9]          [9]
2    Action  [2, 3]       [6, 7]

推荐阅读