我有一個看起來像這樣的資料框:
player school team result exam
a s1 z False English
a s1 z True German
a s1 z True Geography
b s1 z True Geography
b s1 z True History
b s1 z False English
c s1 y False English
d s1 y False German
d s1 y True English
d s1 y True History
e s1 w True German
e s1 w True History
f s1 w False English
該school是永遠不變的。我想player通過公式計算每個的性能(number of Trues) / (number of Trues number of Falses)。但是我想看看每支球隊的平均水平。我會想象這樣的事情(我希望我沒有犯任何計算錯誤):
school team TeamResult
s1 z 0.67
s1 y 0.67
s1 w 0.50
有誰知道我如何“回到”用戶所在的團隊?到目前為止,我嘗試的方法效率極低,即從每個團隊的“大”資料幀中創建新的資料幀,例如df_new = df[df['team'] == 'z']. 還有其他更直接的方法嗎?
uj5u.com熱心網友回復:
你可以使用groupby mean:
df.groupby(['school', 'team'])['result'].mean()
要匹配確切的指定輸出:
(df.groupby(['school', 'team'])
['result'].mean()
.rename('TeamResult')
.sort_values(ascending=False)
.reset_index()
)
輸出:
school team TeamResult
0 s1 w 0.666667
1 s1 z 0.666667
2 s1 y 0.500000
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315277.html
上一篇:以有序的方式洗牌
下一篇:Python 熊貓資料框
