2014-11-03 84 views
0

我試圖使用cumsum()獲取我想在熊貓中得到的結果,但是我卡住了。如何通過cumsum函數跳過熊貓數據框組中的一行

 score1 score2 
team slot  
a 2 4 6 
a 3 3 7 
a 4 2 1 
a 5 4 3 
b 1 7 2 
b 2 2 10 
b 5 1 9 

我的原始數據看起來像上面那樣,我想按照團隊和插槽來計算score1和score2組。我用

df= df.groupby(by=['team','slot']).sum().groupby(level=[0]).cumsum() 

這上面的代碼差點我想要的,但每個團隊都需要整整5插槽像下面的輸出,我怎麼能解決這個問題?

enter image description here

+0

每次重新索引這個答案的最終版本的輸出:http://stackoverflow.com/questions/12390336/how -to-填充的缺失,記錄的 - 大熊貓,數據幀中,Python的路/ 13297472#13297472 – 2014-11-03 22:30:48

回答

1

爲@保羅^ h評論,這裏是代碼:

import io 
import pandas as pd 

text = """team slot score1 score2 
a 2 4 6 
a 3 3 7 
a 4 2 1 
a 5 4 3 
b 1 7 2 
b 2 2 10 
b 5 1 9 
""" 

df = pd.read_csv(io.BytesIO(text), delim_whitespace=True, index_col=[0, 1]) 
df2 = df.reindex(pd.MultiIndex.from_product([df.index.levels[0], range(1, 6)])) 
df2.fillna(0).groupby(level=[0]).cumsum() 
相關問題