熊猫按值将行折叠成元组

时间:2020-10-05 16:49:39

标签: python python-3.x pandas numpy dataframe

我正在尝试将具有相同标题的值的数据框折叠到具有该标题但包含日期的元组的条目中。数据框已经按标识符排序,然后按日期排序。

这是我的数据:

identifier    title     date
123           "Pres"    2019-01-01
123           "Pres"    2020-01-01
123           "CEO"     2020-06-01

我想将其折叠成这样的内容(基于与前一个匹配的标题):

identifier    title     date
123           "Pres"    (2019-01-01, 2020-01-01)
123           "CEO"     (2020-01-01, 2020-06-01) 

任何人都知道哪种功能最好做到这一点?我已经尝试了groupby和agg,但无法使它们正常工作。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

df = df.groupby(['identifier', 'title'], as_index=False).agg(tuple)
print(df)

   identifier title                      date
0         123   CEO             (2020-06-01,)
1         123  Pres  (2019-01-01, 2020-01-01)