Python Pandas:将参数传递给agg()中的函数 [英] Python Pandas: Passing arguments to a function in agg()

查看:2246
本文介绍了Python Pandas:将参数传递给agg()中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用不同类型的函数和参数值来减少熊猫数据框中的数据。但是,我没有设法更改聚合函数中的默认参数。以下是一个例子:

 >>> df = pd.DataFrame({'x':[1,np.nan,2,1],
...'y':['a','a','b','b' ]})
>>> df
xy
0 1.0 a
1 NaN a
2 2.0 b
3 1.0 b

以下是一个聚合函数,我想测试 b 的不同值:

 >>> def translate_mean(x,b = 10):
... y = [elem + b for elem in x]
... return np.mean(y)


$ b

在下面的代码中,我可以将这个函数与默认的 b 值一起使用,但我想传递其他值:

 >>> df.groupby('y')。agg(translate_mean)
x
y
a NaN
b 11.5

有什么想法?

解决方案

只需将参数传递给 agg (这也适用于 apply )。

  df.groupby('y')。agg(translate_mean,b = 4)
Out:
x
y
a NaN
b 5.5


I am trying to reduce data in a pandas dataframe by using different kind of functions and argument values. However, I did not manage to change the default arguments in the aggregation functions. Here is an example:

>>> df = pd.DataFrame({'x': [1,np.nan,2,1],
...                    'y': ['a','a','b','b']})
>>> df
     x  y
0  1.0  a
1  NaN  a
2  2.0  b
3  1.0  b

Here is an aggregation function, for which I would like to test different values of b:

>>> def translate_mean(x, b=10):
...   y = [elem + b for elem in x]
...   return np.mean(y)

In the following code, I can use this function with the default b value, but I would like to pass other values:

>>> df.groupby('y').agg(translate_mean)
      x
y
a   NaN
b  11.5

Any ideas?

解决方案

Just pass as arguments to agg (this works with apply, too).

df.groupby('y').agg(translate_mean, b=4)
Out: 
     x
y     
a  NaN
b  5.5

这篇关于Python Pandas:将参数传递给agg()中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆