问题描述
我想计算分组对象的绝对值的平均值.
I want to compute the mean of the absolute value of a grouped object.
即
grouped = df.groupby([pd.TimeGrouper(3MS)])
dct['x'] = grouped['profit'].agg('mean') / grouped['cost'].abs().agg('mean')
但是,以上代码导致错误.我已经尝试了上述代码的各种变体,但到目前为止,所有这些都会导致错误.
However, the above code results in an error. I have tried various variants of the above code but so far all result in errors.
必须有一种简单的方法来执行此操作.
There must be a simple way to do this.
更新:
这是通过pd.TimeGrouper(3MS)分组的数据帧.我想获取列成本1的绝对值,然后计算平均值.
This is the dataframe that is grouped vi pd.TimeGrouper(3MS). I want to take the absolute value of column cost 1, and then compute the mean.
cost1 cost2 cost3 cost4
date
2016-03-31 -490.60 -118.10 -344.87 -91.44
2016-04-30 -188.74 -55.99 -259.23 -75.16
2016-05-31 -158.62 -43.58 -176.37 -21.98
我尝试做grouped['cost1'].abs().mean()
,但是我得到了:
I tried to do grouped['cost1'].abs().mean()
but I got:
/Users/User1/anaconda/lib/python2.7/site-packages/pandas/core/groupby.pyc in __getattr__(self, attr)
493 return self[attr]
494 if hasattr(self.obj, attr):
--> 495 return self._make_wrapper(attr)
496
497 raise AttributeError("%r object has no attribute %r" %
/Users/User1/anaconda/lib/python2.7/site-packages/pandas/core/groupby.pyc in _make_wrapper(self, name)
507 "using the 'apply' method".format(kind, name,
508 type(self).__name__))
--> 509 raise AttributeError(msg)
510
511 # need to setup the selection
AttributeError: ("Cannot access callable attribute 'abs' of 'SeriesGroupBy' objects, try using the 'apply' method", u'occurred at index 0')
推荐答案
根据您的更新,我认为您正在寻找的是该组绝对值的平均值.
Based on your update, I think you are looking for one mean taken on absolute values for the group.
使用grouped.apply(abs).mean()
会将abs
函数应用于您组中的值(cost1
等),而mean
将为您提供分组变量的平均值.
Using grouped.apply(abs).mean()
will apply the abs
function to values in your group (cost1
etc), and the mean
will give you the average for whatever your grouping variable is.
您也可以在分组之前应用abs
函数,然后直接使用mean
函数.
You could also just apply the abs
function before grouping, and then use the mean
function directly.
这篇关于groupby对象 pandas 的绝对值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!