如何在pandas中跳过一行进行group by cumsum函数
我正在尝试在pandas中使用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进行累加,按照team和slot分组。我使用了
df= df.groupby(by=['team','slot']).sum().groupby(level=[0]).cumsum()
上面的代码几乎达到了我想要的效果,但每个团队需要正好有5个slot,像下面的输出那样,我该如何解决这个问题呢?
1 个回答
1
正如@Paul 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()