Pandas数据透视表Aggfun列表

2024-06-09 08:58:28 发布

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

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'

我如何计算这三个函数?


Tags: 函数代码pandasindexraw字典nppage
3条回答

pivot_tableaggfunc参数接受函数或函数列表,但不接受dict

aggfunc : function, default numpy.mean, or list of functions If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves)

所以试试看

n_page = (pd.pivot_table(Main_DF, 
                         values='SPC_RAW_VALUE',  
                         index=['ALIAS', 'SPC_PRODUCT', 'LABLE', 'RAW_PARAMETER_NAME'], 
                         columns=['LOT_VIRTUAL_LINE'],
                         aggfunc=[len, np.mean, np.std])
          .reset_index()
         )

以后可能需要重命名分层列。

尝试使用groupby

df = (Main_DF
      .groupby(['ALIAS', 'SPC_PRODUCT', 'LABLE', 'RAW_PARAMETER_NAME'], as_index=False)
      .LOT_VIRTUAL_LINE
      .agg({'N': 'count', 'Mean': np.mean, 'Sigma': np.std})
     )

设置as_index=False只需在数据帧中将这些列保留为列,这样以后就不必重置索引。

正如@Happy001在认可答案中所写的,aggfunc不能接受dict是错误的。我们实际上可以把dict传递给aggfunc

一个非常方便的特性是能够将dictionary传递给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,并对Quantitymean执行len操作,对Price执行sum操作。

下面是附加的输出:

enter image description here

这个例子取自pivot table explained.

相关问题 更多 >