简体   繁体   English

pandas聚合具有多个输出列的函数

[英]pandas aggregate function with multiple output columns

I am trying to define an aggregation function with more than one OUTPUT columns, which i would like to use as follows 我试图定义一个具有多个OUTPUT列的聚合函数,我想使用如下

df.groupby(by=...).agg(my_aggregation_function_with_multiple_columns)

any idea how to do it ? 任何想法怎么做?

i tried things like 我尝试过类似的东西

def my_aggregation_function_with_multiple_columns(slice_values):
    return {'col_1': -1,'col_2': 1}

but this will logically output the dictionary {'col_1': -1,'col_2': 1} in a single column... 但这会在单个列中逻辑输出字典{'col_1': - 1,'col_2':1} ...

It is not possible, because agg working with all columns separately - first process first column, then second.... to the end. 这是不可能的,因为agg处理所有列 - 首先处理第一列,然后处理第二列....到最后。

Solution is flexible apply and for return multiple output add Series if output is more scalars. 解决方案是flexible apply和返回多输出添加Series如果输出更多的标量。

def my_aggregation_function_with_multiple_columns(slice_values):
    return pd.Series([-1, 1], index=['col_1','col_2'])

df.groupby(by=...).apply(my_aggregation_function_with_multiple_columns)

Sample: 样品:

df = pd.DataFrame(dict(A=[1,1,2,2,3], B=[4,5,6,7,2], C=[1,2,4,6,9]))
print (df)

def my_aggregation_function_with_multiple_columns(slice_values):
    #print each group
    #print (slice_values)
    a = slice_values['B'] + slice_values['C'].shift()
    print (type(a))
    return a

<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>

df = df.groupby('A').apply(my_aggregation_function_with_multiple_columns)
print (df)
A   
1  0     NaN
   1     6.0
2  2     NaN
   3    11.0
3  4     NaN
dtype: float64

The question can be interpreted in multiple ways. 这个问题可以用多种方式解释。 The following offers a solution for computing more than one output column, giving the possibility to use a different function for each column. 以下提供了计算多个输出列的解决方案,可以为每列使用不同的功能。

The example uses the same Pandas DataFrame df as the answer above: 该示例使用与上述答案相同的Pandas DataFrame df:

import pandas as pd
df = pd.DataFrame(dict(A=[1,1,2,2,3], B=[4,5,6,7,2], C=[1,2,4,6,9]))

As a function of the groups in A the sum of the values in B is computed and put in one column, and the number of values (count) in B is computed and put in another column. 作为A中的组的函数,计算B中的值的总和并将其放入一列中,并且计算B中的值(计数)的数量并将其放入另一列中。

df.groupby(['A'], as_index=False).agg({'B': {'B1':sum, 'B2': "count"}})

Because dictionaries with renaming will be deprecated in future versions the following code may be better: 由于在将来的版本中将弃用具有重命名的字典,因此以下代码可能更好:

df.groupby(['A'], as_index=False).agg({'B': {sum, "count"}})

The next example shows how to do this if you want to have different computations on different columns, for computing the sum of B and mean of C: 下一个示例显示了如果要在不同的列上进行不同的计算,计算B的总和和C的平均值,如何执行此操作:

df.groupby(['A'], as_index=False).agg({'B': sum, 'C': "mean"})

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

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