我有一個這樣的資料框,其中ID和首選項在一個用“,”分隔的字串中:
| ID | 優先 |
|---|---|
| 1 | 香蕉、蘋果 |
| 1 | 香蕉、蘋果、獼猴桃 |
| 1 | 鱷梨,蘋果 |
| 2 | 鱷梨,葡萄 |
| 2 | 香蕉、蘋果、獼猴桃 |
我想按 ID 分組并獲得出現最多的 2 個首選項,所以結果如下:
| ID | first_preference | second_preference |
|---|---|---|
| 1 | 蘋果 | 香蕉 |
| 2 | 鱷梨、葡萄、香蕉、蘋果、獼猴桃 |
將“draws”連接在一起。
我需要在聚合的 groupby上執行此操作,因為我還有其他需要聚合的列。
有人可以幫我嗎?謝謝!
uj5u.com熱心網友回復:
要獲得首選項,首先將您的 DataFrame 拆分并擴展為更長的系列。然后,計算和排列出現次數,另一個groupby agg將允許您加入第一和第二偏好的關系。
此結果的索引將是'ID'原始 DataFrame 中的唯一值,因此您可以concat將其與其他groupby agg操作的結果一起使用
樣本資料
import pandas as pd
df = pd.DataFrame({'ID': [1,1,1,2,2],
'Preferences': ['banana, apple', 'banana, apple, kiwi', 'avocado, apple', 'avocado, grapes',
'banana, apple, kiwi']})
代碼
# Expand to long Series
s = df.set_index(['ID']).Preferences.str.split(', ', expand=True).stack()
# Within each ID, rank preferences based on # of occurrences
s = (s.groupby([s.index.get_level_values(0), s.rename('preference')]).size()
.groupby(level=0).rank(method='dense', ascending=False)
.map({1: 'first', 2: 'second'}).rename('order'))
res = s[s.isin(['first', 'second'])].reset_index().groupby(['ID', 'order']).agg(', '.join).unstack(-1)
# Collapse MultiIndex to get simple column labels
res.columns = [f'{y}_{x}' for x,y in res.columns]
print(res)
first_preference second_preference
ID
1 apple banana
2 apple, avocado, banana, grapes, kiwi NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479567.html
