【问题标题】:Pandas collapse rows by value into tuplePandas 按值将行折叠成元组
【发布时间】:2020-10-05 16:49:39
【问题描述】:

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

这是我的数据的样子:

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 但无法让它们工作。

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 优秀的答案。谢谢@NYC Coder,我今天学到了一些新东西。
    猜你喜欢
    • 2020-03-20
    • 2019-08-07
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2020-12-14
    • 1970-01-01
    相关资源
    最近更新 更多