估算RollingGroupby的加权平均值

时间:2018-06-06 20:53:05

标签: python pandas numpy

我想计算RollingGroupby对象的加权平均值。不幸的是,我收到了一个错误:

np.random.seed(9999)
df = pd.DataFrame(np.random.random(20).reshape(10, 2), columns = ['val1', 'val2'])
df['id'] = np.repeat([1, 2], 5)
df['wt'] = [1, 2] * 5

def weighted_average(data, value, weight):
    return np.average(data[value], weights = data[weight], axis = 0)

dfwavg = df.groupby('id')[['val1', 'wt']]\
        .rolling(window=2, min_periods=1)\
        .apply(weighted_average, 'wt')

这是我的代码:

apply()

有人知道这是什么问题吗?感谢。

修改

如果解决方案使用现有结构(使用group.by.rolling.apply)会很棒。换句话说,最好的选择可能是将修改过的函数嵌套在static void Main(string[] args) { int result = 0; Console.WriteLine("Give me a number over 5 bro"); int x = int.Parse(Console.ReadLine()); try{ result = AddNumbers(x, 5); Console.WriteLine(result); }catch(Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("Press enter to close..."); Console.ReadLine(); } public static int AddNumbers(int number1, int number2) { int result = number1 + number2; if (result > 10) { return result; } else throw new Exception("brah I've told ya that I want more than 5"); }

1 个答案:

答案 0 :(得分:0)

喜欢这个?

pd.concat([(x.val1*x.wt).rolling(window=2,min_periods=1).sum()/x.wt.rolling(window=2,min_periods=1).sum() for _,x in df.groupby('id')])
Out[592]: 
0    0.823389
1    0.295437
2    0.072459
3    0.333050
4    0.445683
5    0.913049
6    0.704820
7    0.317114
8    0.325059
9    0.179366
dtype: float64