gpt4 book ai didi

python - Aggfunc 的 Pandas 数据透视表列表

转载 作者:太空狗 更新时间:2023-10-29 21:14:40 24 4
gpt4 key购买 nike

Agg函数的Pandas数据透视表字典

我正在尝试在旋转期间计算 3 个 aggregative 函数:

  1. 计数
  2. 均值
  3. 标准差

这是代码:

n_page = (pd.pivot_table(Main_DF, 
values='SPC_RAW_VALUE',
index=['ALIAS', 'SPC_PRODUCT', 'LABLE', 'RAW_PARAMETER_NAME'],
columns=['LOT_VIRTUAL_LINE'],
aggfunc={'N': 'count', 'Mean': np.mean, 'Sigma': np.std})
.reset_index()
)

我得到的错误是:KeyError: 'Mean'

如何计算这 3 个函数?

最佳答案

正如@Happy001 在批准的答案中所写,aggfunc cant take dict 是错误的。我们实际上可以将 dict 传递给 aggfunc

一个非常方便的功能是能够将字典传递给aggfunc,这样您就可以对您选择的每个值执行不同的功能。例如:

import pandas as pd
import numpy as np

df = pd.read_excel('sales-funnel.xlsx') #loading xlsx file

table = pd.pivot_table(df, index=['Manager', 'Status'], columns=['Product'], values=['Quantity','Price'],
aggfunc={'Quantity':len,'Price':[np.sum, np.mean]},fill_value=0)
table

在上面的代码中,我将 dictionary 传递给 aggfunc 并对 Quantity 和执行 len 操作meansumPrice 的运算。

这是附加的输出:

enter image description here

示例取自pivot table explained.

关于python - Aggfunc 的 Pandas 数据透视表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com