在大 pandas 的变换中应用几个函数 [英] applying several functions in transform in pandas
问题描述
在groupby
之后,使用agg
时,如果传入一个columns:functions
的dict,函数会被应用到对应的列.然而,这种语法不适用于 transform
.在transform
中还有其他方法可以应用多个函数吗?
After a groupby
, when using agg
, if a dict of columns:functions
is passed, the functions will be applied in the corresponding columns. Nevertheless this syntax doesn't work with transform
. Is there another way to apply several functions in transform
?
举个例子:
import pandas as pd
df_test = pd.DataFrame([[1,2,3],[1,20,30],[2,30,50],[1,2,33],[2,4,50]],columns = ['a','b','c'])
Out[1]:
a b c
0 1 2 3
1 1 20 30
2 2 30 50
3 1 2 33
4 2 4 50
def my_fct1(series):
return series.mean()
def my_fct2(series):
return series.std()
df_test.groupby('a').agg({'b':my_fct1,'c':my_fct2})
Out[2]:
c b
a
1 16.522712 8
2 0.000000 17
前面的例子展示了如何在agg
中对不同的列应用不同的函数,但是如果我们想转换列而不聚合它们,则不能使用agg
了.因此:
The previous example shows how to apply different function to different columns in agg
, but if we want to transform the columns without aggregating them, agg
can't be used anymore. Therefore:
df_test.groupby('a').transform({'b':np.cumsum,'c':np.cumprod})
Out[3]:
TypeError: unhashable type: 'dict'
我们如何使用以下预期输出执行这样的操作:
How can we perform such an action with the following expected output:
a b c
0 1 2 3
1 1 22 90
2 2 30 50
3 1 24 2970
4 2 34 2500
推荐答案
我认为现在 (pandas 0.20.2) 函数 transform
不是用 dict
实现的 - 列名称的功能类似于 <代码>agg.
I think now (pandas 0.20.2) function transform
is not implemented with dict
- columns names with functions like agg
.
如果函数返回相同长度的Series
:
If functions return Series
with same lenght:
df1 = df_test.set_index('a').groupby('a').agg({'b':np.cumsum,'c':np.cumprod}).reset_index()
print (df1)
a c b
0 1 3 2
1 1 90 22
2 2 50 30
3 1 2970 24
4 2 2500 34
但是如果聚合不同的长度需要加入
:
But if aggreagte different length need join
:
df2 = df_test[['a']].join(df_test.groupby('a').agg({'b':my_fct1,'c':my_fct2}), on='a')
print (df2)
a c b
0 1 16.522712 8
1 1 16.522712 8
2 2 0.000000 17
3 1 16.522712 8
4 2 0.000000 17
这篇关于在大 pandas 的变换中应用几个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!