在客户id列的pandas中创建一个列,其中包含每个客户使用groupby所拥有的产品列表



我有一个数据帧,如下所示

df

cust_id         product
1               tv
1               phone
2               bat
2               ball
3               bat
4               ball
4               bat
4               tv
4               phone
5               tv
6               bat
7               bat
7               ball
7               tv
8               phone
8               tv

根据以上内容,我想准备下面的数据框架,如下所示。如果product_list列由产品列表组成,则列表中的元素应按发送顺序排序。

预期输出:

cust_id           product_list
1                 ['phone', 'tv']
2                 ['ball', 'bat']
3                 ['bat']
4                 ['ball', 'bat', 'phone', 'tv']
5                 ['tv']
6                 ['bat']
7                 ['ball', 'bat', 'phone', 'tv']       
8                 ['phone', 'tv']

我尝试了低于代码

df1 = df.groupby('cust_id').agg(product_list=('product','unique')).reset_index()
df1
cust_id   product_list
0   1         [tv, phone]
1   2         [bat, ball]
2   3         [bat]
3   4         [ball, bat, tv, phone]
4   5         [tv]
5   6         [bat]
6   7         [bat, ball, tv]
7   8         [phone, tv]

但这并不是我想要的。

我尝试了以下代码以及

s = df.groupby('cust_id')['product'].apply(list).reset_index()
s.rename({'product':'product_list'}, axis=1, inplace=True)
s

我得到的是如下

cust_id product_list
0   1   [tv, phone]
1   2   [bat, ball]
2   3   [bat]
3   4   [ball, bat, tv, phone]
4   5   [tv]
5   6   [bat]
6   7   [bat, ball, tv]
7   8   [phone, tv]

IIUC需要引号中的值。有一种方法

df.groupby('cust_id')['product'].apply(lambda x: [', '.join("'" + item + "'" for item in sorted(x))]).reset_index()

cust_id     product
0         1     ['phone', 'tv']
1         2     ['ball', 'bat']
2         3     ['bat']
3         4     ['ball', 'bat', 'phone', 'tv']
4         5     ['tv']
5         6     ['bat']
6         7     ['ball', 'bat', 'tv']
7         8     ['phone', 'tv']

在聚合前对数据进行排序:

df1 = (df.sort_values(['cust_id', 'product'])
.groupby('cust_id')['product'].agg(list)
.reset_index(name='product_list')
)

输出:

cust_id            product_list
0        1             [phone, tv]
1        2             [ball, bat]
2        3                   [bat]
3        4  [ball, bat, phone, tv]
4        5                    [tv]
5        6                   [bat]
6        7         [ball, bat, tv]
7        8             [phone, tv]

最新更新