Pandas 包含特定值的行的加权平均值
Pandas weighted average on rows that contain a certain value
我有一个按日期索引的数据框,如下所示:
date id1 id2 id3 identifier x_times value
2016-01-01 123 1234 12345 a 21 56
2016-01-01 123 1234 12345 b 2 78
2016-01-01 123 1234 12345 c 10 23
我需要执行加权平均计算,其中每个日期的标识符仅为 a 和 b。计算应该是:
((56 * 21) + (78 * 2)) / (21 + 2) = 57.91
输出:
date id1 id2 id3 identifier x_times value weighted_avg
2016-01-01 123 1234 12345 a 21 56 57.91
2016-01-01 123 1234 12345 b 2 78 57.91
2016-01-01 123 1234 12345 c 10 23
我已经尝试过 group bys 和 sums,但我很难将数据框与加权平均值一起重新加入。
执行此计算的最简单方法是什么?谢谢!
您可以使用 isin
method to subset your original dataframe to smaller one. Then you could do your calculations with that subset dataframe and then using loc
将其分配给原始数据框:
subs = df.identifier.isin(['a','b'])
df_subs = df[subs]
df.loc[subs, 'weighted_avg'] = (df_subs.x_times * df_subs.value).sum() / df_subs.x_times.sum()
In [670]: df
Out[670]:
id1 id2 id3 identifier x_times value weighted_avg
date
2016-01-01 123 1234 12345 a 21 56 57.913043
2016-01-01 123 1234 12345 b 2 78 57.913043
2016-01-01 123 1234 12345 c 10 23 NaN
我有一个按日期索引的数据框,如下所示:
date id1 id2 id3 identifier x_times value
2016-01-01 123 1234 12345 a 21 56
2016-01-01 123 1234 12345 b 2 78
2016-01-01 123 1234 12345 c 10 23
我需要执行加权平均计算,其中每个日期的标识符仅为 a 和 b。计算应该是:
((56 * 21) + (78 * 2)) / (21 + 2) = 57.91
输出:
date id1 id2 id3 identifier x_times value weighted_avg
2016-01-01 123 1234 12345 a 21 56 57.91
2016-01-01 123 1234 12345 b 2 78 57.91
2016-01-01 123 1234 12345 c 10 23
我已经尝试过 group bys 和 sums,但我很难将数据框与加权平均值一起重新加入。
执行此计算的最简单方法是什么?谢谢!
您可以使用 isin
method to subset your original dataframe to smaller one. Then you could do your calculations with that subset dataframe and then using loc
将其分配给原始数据框:
subs = df.identifier.isin(['a','b'])
df_subs = df[subs]
df.loc[subs, 'weighted_avg'] = (df_subs.x_times * df_subs.value).sum() / df_subs.x_times.sum()
In [670]: df
Out[670]:
id1 id2 id3 identifier x_times value weighted_avg
date
2016-01-01 123 1234 12345 a 21 56 57.913043
2016-01-01 123 1234 12345 b 2 78 57.913043
2016-01-01 123 1234 12345 c 10 23 NaN