与我之前的问题类似,我想按组拆分数据框并应用计算。
现在我想引入一个新列来将计算拆分到数据框中。以下是代码:
import pandas as pd
import numpy as np
d = {'year' : [2000, 2000, 2000, 2000, 2001, 2001, 2001],
'home': ['A', 'B', 'B', 'A', 'B', 'A', 'A'],
'away': ['B', 'A', 'A', 'B', 'A', 'B', 'B'],
'aw': [1, 0, 0, 0, 1, 0, np.nan],
'hw': [0, 1, 0, 1, 0, 1, np.nan]}
df = pd.DataFrame(d, columns=['home', 'away', 'hw', 'aw'])
df.index = range(1, len(df) + 1)
df.index.name = 'game'
df = df.set_index(['hw', 'aw'], append=True).stack().reset_index().rename(columns={'level_3': 'role', 0: 'team'}).loc[:,
['game', 'team', 'role', 'hw', 'aw']]
def wins(row):
if row['role'] == 'home':
return row['hw']
else:
return row['aw']
df['wins'] = df.apply(wins, axis=1)
df['expanding_mean'] = df.groupby('team')['wins'].apply(lambda x: pd.expanding_mean(x).shift())
print df
运行上述代码将在整个数据框上生成扩展平均值。但是如何针对每个新的 "year" 重新开始计算呢?
我尝试在 df 声明中添加 year 到 columns=,但它包含在 role 中,这是不期望的。我的理解差距在于层次结构,任何启示都将不胜感激。
编辑:以下是所需结果。
game team role hw aw wins expanding_mean year
0 1 A home 0 1 0 NaN 2000
1 1 B away 0 1 1 NaN 2000
2 2 B home 1 0 1 1.000000 2000
3 2 A away 1 0 0 0.000000 2000
4 3 B home 0 0 0 1.000000 2000
5 3 A away 0 0 0 0.000000 2000
6 4 A home 1 0 1 0.000000 2000
7 4 B away 1 0 0 0.666667 2000
8 5 B home 0 1 0 NaN 2001
9 5 A away 0 1 1 NaN 2001
10 6 A home 1 0 1 0.000000 2001
11 6 B away 1 0 0 1.000000 2001
12 7 A home NaN NaN NaN 0.500000 2001
13 7 B away NaN NaN NaN 0.500000 2001
df.groupby(['team', 'year'])
。 - MaxNoe