Python 按查询分组

Python 按查询分组,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我在pandas中有一个数据帧,如下所示: 现在,我希望将数据帧转换为如下所示,其中属性“category”通过基于排序日期值(%m/%d/%Y)的每个customerid的分隔符连接起来。日期较早的订单将其类别列在相应客户id的第一位 首先将列转换为,然后使用连接: df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y') df = (df.sort_values(['customerid','Age','Date'])

我在pandas中有一个数据帧,如下所示:

现在,我希望将数据帧转换为如下所示,其中属性“category”通过基于排序日期值(%m/%d/%Y)的每个customerid的分隔符连接起来。日期较早的订单将其类别列在相应客户id的第一位

首先将列转换为,然后使用
连接

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

同一客户的年龄是否会不同,因为您有与每行关联的日期?在转换后的数据帧中应该如何处理它?@ALollz age wold没有区别。日期列应放在末尾。