python - 使用 pivot_table 时应用不同的聚合函数

标签 python python-3.x pandas dataframe

我有这个样本:

import pandas as pd
import numpy as np
dic = {'name':
       ['j','c','q','j','c','q','j','c','q'],
       'foo or bar':['foo','bar','bar','bar','foo','foo','bar','foo','foo'], 
       'amount':[10,20,30, 20,30,40, 200,300,400]}
x = pd.DataFrame(dic)
x
pd.pivot_table(x, 
               values='amount', 
               index='name', 
               columns='foo or bar', 
               aggfunc=[np.mean, np.sum])

它返回这个:

enter image description here

我只想要突出显示的列。为什么我不能像这样在 aggfunc 参数中指定元组?

pd.pivot_table(x, 
               values='amount', 
               index='name', 
               columns='foo or bar', 
               aggfunc=[(np.mean, 'bar'), (np.sum, 'foo')])

像这里一样使用 .ix (define aggfunc for each values column in pandas pivot table) 是唯一的选择吗?

最佳答案

我认为你不能为 aggfunc 参数指定元组,但你可以这样做:

In [259]: p = pd.pivot_table(x,
   .....:                values='amount',
   .....:                index='name',
   .....:                columns='foo or bar',
   .....:                aggfunc=[np.mean, np.sum])

In [260]: p
Out[260]:
           mean       sum
foo or bar  bar  foo  bar  foo
name
c            20  165   20  330
j           110   10  220   10
q            30  220   30  440

In [261]: p.columns = ['{0[0]}_{0[1]}'.format(col) if col[1] else col[0] for col in p.columns.tolist()]

In [262]: p.columns
Out[262]: Index(['mean_bar', 'mean_foo', 'sum_bar', 'sum_foo'], dtype='object')

In [264]: p[['mean_bar','sum_foo']]
Out[264]:
      mean_bar  sum_foo
name
c           20      330
j          110       10
q           30      440

关于python - 使用 pivot_table 时应用不同的聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114645/

相关文章:

python - Dask Dataframe 列总和始终返回标量

python交互模式模块导入问题

python-3.x - 使用 pytest,如何将 pathlib 的 Path.isdir() 函数与 os.listdir 一起模拟

python-3.x - 生成随机整数,但每次都需要不同

python - python 在 float 前插入逗号

python - pandas.nlargest() - 与重复的索引值混淆

Python:如何检查值列表是否包含在某个范围内

c++ - 将数据从 Django 传递到 C++ 应用程序并返回

python - pydev 语法突出显示 python 内置函数

python - 如何遍历数组数组中的键?