熊猫集团查询

时间:2019-02-24 07:16:16

标签: python pandas pandas-groupby

我在熊猫中有一个数据框,如下所示: Snapshot of my pandas dataframe

现在,我希望像下面这样对数据帧进行转换,其中,基于排序的日期值(%m /%d /%Y),每个客户id的定界符属性“ category”被分隔符分隔开。日期较早的订单的类别首先列出对应的客户ID。

Desired/Transformed data frame

1 个答案:

答案 0 :(得分:0)

首先将列转换为to_datetime,然后将sort_values转换为join,最后groupby

df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')

df = (df.sort_values(['customerid','Age','Date'])
        .groupby(['customerid','Age'])['category']
        .agg(', '.join)
        .reset_index())
print (df)
   customerid  Age               category
0           1   10  Electronics, Clothing
1           2   25      Grocery, Clothing