[英]Use pandas groupby to find unique combinations of columns and save as df
我有以下熊貓數據框:
df = pd.DataFrame({'Colors': ['blue', 'blue', 'orange', 'red',
'purple', 'orange', 'purple', 'blue', 'brown'],
'Price': ['500', '500', '200', '250', '300', '765', '1100', '762',
'650', '625'],
'Style': ['farm', 'contemporary', 'modern', 'MDM', 'MDM',
'contemporary', 'farm', 'contemporary', 'farm'],
'Location': ['far', 'near', 'far', 'far', 'near', 'far', 'far', 'near',
'far']})
我可以執行df.groupby(['Colors', 'Price', 'Style', 'Location']).size()
以按顏色進行細分以查看價格、樣式和位置 wrt 的獨特組合返回為一系列的。
問題 - 我如何使用它來創建一個新的 Pandas Dataframe,其中每列對應一種顏色(藍色、橙色、紅色等)和值的唯一組合(500_contemporary_near、500_farm_far 等)?
我嘗試生成的輸出示例是一個 dataFrame,其中有一列名為“Blue”,(每行)下的每個值都是一個字符串,例如 500_contemporary_near。
500_contemporary_near
500_farm_far
你可以做unstack
df.groupby(['Colors', 'Price', 'Style', 'Location']).size().unstack(level=0)
這個怎么樣:
pd.DataFrame([{k[0]: '_'.join(k[1:])} for k in \
df.groupby(['Colors','Price', 'Style', 'Location']).groups]).fillna('')
blue brown orange purple red
0 500_contemporary_near
1 500_farm_far
2 762_contemporary_near
3 650_farm_far
4 200_modern_far
5 765_contemporary_far
6 1100_farm_far
7 300_MDM_near
8 250_MDM_far
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.