給定這樣的數據框:
客戶 | 優先事項 |
---|---|
客戶 1 | 低的 |
客戶 1 | 中等的 |
客戶 2 | 低的 |
客戶 2 | 高的 |
客戶 3 | 低的 |
我想按客戶端分組並為每個客戶端選擇最高優先級(低、中、高)。它應該是這樣的:
客戶 | 優先事項 |
---|---|
客戶 1 | 中等的 |
客戶 2 | 高的 |
客戶 3 | 低的 |
priority
在分組之前轉換為分類列:
dtype = pd.CategoricalDtype(['High', 'Medium', 'Low'], ordered = True)
df['Priority'] = df.Priority.astype(dtype)
df.sort_values(['Client', 'Priority']).groupby('Client', sort = False).head(1)
Client Priority
1 Client 1 Medium
3 Client 2 High
4 Client 3 Low
如果您不想轉換為類別,則可以映射位置:
(df.assign(temp = df.Priority.map({'Low':3,'Medium':2, 'High':1}))
.sort_values(['Client', 'temp'])
.drop(columns='temp')
.groupby('Client')
.head(1)
)
Client Priority
1 Client 1 Medium
3 Client 2 High
4 Client 3 Low
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句