Fel*_*lix 7 python pivot-table pandas
Pandas Pivot表Agg函数字典
我试图aggregative
在旋转期间计算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()
)
Run Code Online (Sandbox Code Playgroud)
我得到的错误是: KeyError: 'Mean'
我该如何计算这3个函数?
小智 16
正如@ 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
Run Code Online (Sandbox Code Playgroud)
在上面的代码,我传递dictionary
到aggfunc
和执行len
上的操作Quantity
和mean
,sum
操作上Price
.
这是附加的输出:
该示例取自枢轴表解释.
该aggfunc
的参数pivot_table
需要的功能的功能或列表,但不dict
aggfunc:function,默认numpy.mean或函数列表如果传递的函数列表,生成的数据透视表将具有分层列,其顶层是函数名称(从函数对象本身推断)
所以试试吧
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()
)
Run Code Online (Sandbox Code Playgroud)
您可能希望之后重命名分层列.
归档时间: |
|
查看次数: |
27274 次 |
最近记录: |