Pandas数据透视表加权平均值

2024-03-28 22:34:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在计算熊猫数据透视表中的加权平均价格。在

我尝试过使用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个值BalancePrice):

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


Tags: 数据dfdatanptableproductpricedict
1条回答
网友
1楼 · 发布于 2024-03-28 22:34:22

我想你可以修改你的代码

df.groupby(['Product', 'Delivery']).\
    apply(lambda x: pd.Series([np.average(x.Price, weights=x.Balance),x.Balance.sum()],index=['Price','Balance'])).unstack()
Out[21]: 
              Price                 Balance                
Delivery    2019-01 2019-02 2019-03 2019-01 2019-02 2019-03
Product                                                    
A         93.333333   100.0   105.0   150.0   150.0   200.0
B         93.333333   100.0   105.0   150.0   150.0   200.0
C         93.333333   100.0   105.0   150.0   150.0   200.0

相关问题 更多 >