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

标签 python pandas pivot-table

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/

相关文章:

python - Scikit-learn 交叉验证分数 : too many indices for array

Python (3.4) 字典/树扁平化时未调用递归函数

python - 在 Pandas 中按日期获取有效合约

mysql - 如何在 MySQL 中返回数据透视表输出?

excel - 如果 CubeField.Orientation = xlPageField 如何设置 PivotField.HiddenItemsList 属性的值

python - 表单清理方法与模型清理方法与模型字段验证器

python - 我应该在 PyCrypto 2.0.1 的 RSA.generate() 中为 randfunc 使用什么?

python - Pandas Dataframe 从分组中选择随机行,并找到每个分组的平均值

python - pd.read_csv 的小数问题

python - 将数据透视表转换为数据框