我在计算熊猫数据透视表中的加权平均价格。在
我尝试过使用groupby,它可以很好地与np.average
配合使用。但是,我无法使用pd.pivot_table
复制它。在
我从字典中构造了数据帧:
dict_data = {
'Contract' : ['Contract 1', 'Contract 2', 'Contract 3', 'Contract 4', 'Contract 5', 'Contract 6', 'Contract 7', 'Contract 8', 'Contract 9', 'Contract 10', 'Contract 11', 'Contract 12'],
'Contract_Date': ['01/01/2019', '02/02/2019', '03/03/2019', '04/03/2019', '01/01/2019', '02/02/2019', '03/03/2019', '04/03/2019', '01/01/2019', '02/02/2019', '03/03/2019', '04/03/2019'],
'Product': ['A','A','A','A','B','B','B','B', 'C','C','C','C'],
'Delivery' : ['2019-01', '2019-01', '2019-02', '2019-03', '2019-01', '2019-01', '2019-02', '2019-03', '2019-01', '2019-01', '2019-02', '2019-03'],
'Price' : [90, 95, 100, 105, 90, 95, 100, 105, 90, 95, 100, 105],
'Balance': [50, 100, 150, 200, 50, 100, 150, 200, 50, 100, 150, 200]
}
df = pd.DataFrame.from_dict(dict_data)
df
^{pr2}$
使用groupby进行加权平均计算:
df.groupby(['Product', 'Delivery']).apply(lambda x: np.average(x.Price, weights=x.Balance))
输出:
Product Delivery
A 2019-01 93.333333
2019-02 100.000000
2019-03 105.000000
B 2019-01 93.333333
2019-02 100.000000
2019-03 105.000000
C 2019-01 93.333333
2019-02 100.000000
2019-03 105.000000
已经尝试并陷入以下困境:
# Define a dictionary with the functions to apply for a given column:
f = {'Balance': ['sum'], 'Price': [np.average(df.Price, weights=df.Balance)] }
# Construct a pivot table, applying the weighted average price function to 'Price'
df.pivot_table(
columns='Delivery',
values=['Balance', 'Price'],
index='Product',
aggfunc=f
).swaplevel(1,0,axis=1).sort_index(axis=1)
共享列Delivery
下的预期输出(显示2个值Balance
和Price
):
Delivery 2019-01 2019-02 2019-03
Balance Price Balance Price Balance Price
Product
A 150 93.333 150 100 200 105
B 150 93.333 150 100 200 105
C 150 93.333 150 100 200 105
我想你可以修改你的代码
相关问题 更多 >
编程相关推荐