我有一个 Pandas 数据框
import pandas as pd
df = pd.DataFrame({'Col1' : 16 * ['A', 'B', 'C'],
'Col2' : np.random.rand(48),
'Col3' : np.random.randint(5, 20, 48)},
index = pd.date_range('2017-01-01', periods=48, freq='H'))
In [1]: df.tail()
Out [1]:
Col1 Col2 Col3
2017-01-02 19:00:00 B 0.144572 7
2017-01-02 20:00:00 C 0.740500 11
2017-01-02 21:00:00 A 0.357077 19
2017-01-02 22:00:00 B 0.652536 9
2017-01-02 23:00:00 C 0.022437 8
我想返回一个数据框,该数据框按日期显示 Col3 的加权平均值,其中 Col2 是权重,Col1 是“B”或“C”,同时忽略“A”。这将返回如下所示的内容。
WtdAvg
2017-01-01 XX.X
2017-01-02 YY.Y
最佳答案
过滤 DataFrame 以删除 Col1 为“A”的值,然后使用 np.average
执行 groupby
:
df[df['Col1'] != 'A'].groupby(pd.TimeGrouper('D')) \
.apply(lambda grp: np.average(grp['Col3'], weights=grp['Col2']))
结果输出(使用 np.random.seed([3,1415])
作为随机状态种子):
2017-01-01 11.975517
2017-01-02 12.411798
关于python - 根据 pandas 数据框第 3 列中的标准,按天分组的 2 列的加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602026/