简体   繁体   English

使用交叉表在 Pandas 中聚合具有不同聚合函数的多个列

[英]Aggregate Multiple columns with different agg functions in Pandas using Crosstab

I have a dataframe of the below format.我有以下格式的 dataframe。 Let us call it df让我们称之为 df

flag1标志 1 flag2标志2 type类型 count1计数 1 count2 count2
a一种 x X new新的 10 10 2 2个
a一种 y old老的 40 40 5 5个
a一种 x X old老的 50 50 6 6个
a一种 y new新的 15 15 1 1个

I am trying to get the following format.我正在尝试获取以下格式。 (I could not merge the adjacent cells of count1 and count2) (我无法合并 count1 和 count2 的相邻单元格)

count1计数 1 count2 count2
new新的 old老的 new新的 old老的
a一种 x X 10 10 50 50 2 2个 6 6个
a一种 y 15 15 40 40 1 1个 5 5个

I tried the following when i had to do the aggregate on only one column (count1) and the following worked:当我不得不只对一列 (count1) 进行聚合时,我尝试了以下操作,并且以下操作有效:

pd.crosstab([df.flag1,df.flag2], df.type, values=df.count1, aggfunc='sum') 

But since i want two columns of data, both count1 and count2, I tried the following but did not work out但是由于我想要两列数据,count1 和 count2,我尝试了以下但没有成功

pd.crosstab([df.flag1,df.flag2], df.type, values=[df.count1,df.count2], aggfunc=['sum','sum']) #trial1
pd.crosstab([df.flag1,df.flag2], df.type, values=[df.count1,df.count2], aggfunc='sum') #trial2

None of them worked.他们都没有工作。

Extension : I should be able use different functions on the different columns.扩展:我应该能够在不同的列上使用不同的功能。 say sum on count1 and nunique on count2 or sum on count1 and mean on count2在 count1 上求和,在 count2 上求和,或者在 count1上求和,在 count2 上求和

I think crosstab is not possible use here, alternative is DataFrame.pivot_table :我认为这里不可能使用crosstab ,替代方案是DataFrame.pivot_table

df = df.pivot_table(index=['flag1','flag2'], 
                    columns='type', 
                    aggfunc={'count1':'sum', 'count2':'nunique'})
print (df)
            count1     count2    
type           new old    new old
flag1 flag2                      
a     x         10  50      1   1
      y         15  40      1   1

Another alternative with aggregation:聚合的另一种选择:

df = (df.groupby(['flag1','flag2','type'])
        .agg({'count1':'sum', 'count2':'nunique'})
        .unstack())
print (df)
            count1     count2    
type           new old    new old
flag1 flag2                      
a     x         10  50      1   1
      y         15  40      1   1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM