我有一個如下所示的資料框
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]
uj5u.com熱心網友回復:
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']
uj5u.com熱心網友回復:
聚合前的資料排序:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505750.html
標籤:python-3.x 熊猫 数据框 通过...分组
上一篇:Pandas長格式成功表
