2017-10-05 1397 views
0

我想要生成一個數據透視表,其結果如下 想知道我是如何計算win,lost和draw的......# 本質上,我想說的只是如果Result == 「贏」Python數據透視表條件計數

我不想使用結果爲一列,因爲我不希望有按WIN /失落的速度擊穿/抽獎......是有辦法算了算的

Name Result  Win Loss Draw Speed 
James 6   2  2  2  50 
Bob  9   7  2  0  48 
Mary  10  5  3  2  70 

這是代碼

report = pd.pivot_table(df,index=["Name"], values=["Result", "Speed"], aggfunc= {"Result": len, "Speed": np.mean}, fill_value=0) 

預先感謝您

+1

「張數」,究竟是什麼? – jrd1

+0

@ jrd1我正在計算Win/Loss/Draw的數量,在Result Column中,它是Win/Loss/Draw ....的一個字符串,所以當我做「len」時,我得到結果數。 ..但我想過濾的勝利數量....所以我猜只有如果勝利len? – Jister

+0

@ jrd1換句話說,雖然Result:len給了我每個人玩的遊戲數量,有沒有一種方法可以讓我計算Wins ....#沒有Result作爲列 – Jister

回答

0

假設你的數據看起來是這樣的:

# sample data 
df = pd.DataFrame({ 
    'Name' : ['James']*6 +\ 
      ['Bob']*9 +\ 
      ['Mary']*10, 
    'Result' : ['Win']*2 + ['Loss']*2 + ['Draw']*2 +\ 
       ['Win']*7 + ['Loss']*2 +\ 
       ['Win']*5 + ['Loss']*3 + ['Draw']*2, 
    'Speed' : [50]*6 +\ 
       [48]*9 +\ 
       [70]*10 
}) 

df

然後,只需在 '贏' 過濾器和數據透視:

# Filter on 'Win'; make pivot table 
df[df.Result == 'Win'].pivot_table(index = 'Name', 
            values = ['Result', 'Speed'], 
            aggfunc = {'Result' : 'count', 
               'Speed' : 'mean'}, 
            fill_value = 0).rename(columns = {'Result' : 'Win'}) 

或者GROUPBY和聚合:

# groupby.agg() 
df[df.Result == 'Win'].groupby('Name').agg({'Result' : 'count', 
              'Speed' : 'mean'}).rename({'Result' : 'Win'}) 

的結果相同:

result