Agg函数的Pandas数据透视表字典
我正在尝试在旋转期间计算 3 个 aggregative
函数:
- 计数
- 均值
- 标准差
这是代码:
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
操作mean
,sum
对 Price
的运算。
这是附加的输出:
关于python - Aggfunc 的 Pandas 数据透视表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193862/