![](/img/trans.png)
[英]Python pandas: How to group by and count unique values based on multiple columns?
[英]How to group , count, and unstack a pandas dataframe based on multiple columns values?
我有以下 pandas 數據框,其中存儲了多個模型和多家公司的贏/輸結果
公司 | 型號_1 | 溫洛斯 | 型號_2 | 輸贏2 |
---|---|---|---|---|
公司1 | 神經網絡 | W | 探地雷達 | 大號 |
公司1 | 神經網絡 | 大號 | PLS | W |
公司1 | 神經網絡 | 大號 | KRR | W |
公司1 | 神經網絡 | 大號 | XGB | W |
公司1 | 探地雷達 | 大號 | 新元 | W |
公司2 | 探地雷達 | 大號 | PLS | W |
公司2 | KRR | 大號 | XGB | W |
我想按公司和模型進行分組,並計算同一公司內每個模型的贏損,以便我以后可以將結果分解為如下所示的輸出:
('公司', '') | ('DT','L') | ('DT','W') | ('GPR','L') | ('KNN','L') | ('KNN','W') | ('KRR','W') | ('PLS','W') | ('SGD', 'W') | ('SVR','L') | ('SVR','W') |
---|---|---|---|---|---|---|---|---|---|---|
公司1 | 3.0 | 2.0 | 5.0 | 3.0 | 1.0 | 1.0 | 1.0 | 1.0 | 2.0 | 1.0 |
公司2 | 6.0 | 2.0 | 0.0 | 2.0 | 1.0 | 0.0 | 0.0 | 0.0 | 6.0 | 1.0 |
公司3 | 0.0 | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
公司4 | 6.0 | 1.0 | 5.0 | 0.0 | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 |
公司5 | 7.0 | 1.0 | 5.0 | 0.0 | 1.0 | 0.0 | 0.0 | 0.0 | 0.0 | 2.0 |
上表是我以下代碼的結果,但計數值的數字結果不准確:
WLPerCompany = WinLoss.groupby(['company','Model_1','Winloss'])
['Winloss'].count()
WinLossResults = pd.DataFrame(WLPerCompany)
WinLossResults.columns = [*WinLossResults.columns[:-1], 'counts']
WinLossResults= WinLossResults['counts'].unstack(level=['Model_1',
'Winloss'])
WinLossResults= WinLossResults.fillna(0)
WinLossResults
先使用wide_to_long
進行整形,然后再使用crosstab
:
df = pd.wide_to_long(df.reset_index().rename(columns={'Winloss':'Winloss1'}),
stubnames=['Model_','Winloss'],
i=['index','company'],
j='tmp').reset_index()
df = pd.crosstab(df['company'], [df['Model_'], df['Winloss']])
print (df)
Model_ GPR KNN KRR PLS SGD XGB
Winloss L L W L W W W W
company
Company1 2 3 1 0 1 1 1 1
Company2 1 0 0 1 0 1 0 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.