groupby 对象的绝对值的平均值 pandas
mean of absolute value of groupby object pandas
我想计算分组对象的绝对值的平均值。
即
grouped = df.groupby([pd.TimeGrouper(3MS)])
dct['x'] = grouped['profit'].agg('mean') / grouped['cost'].abs().agg('mean')
但是,上面的代码会导致错误。我已经尝试了上述代码的各种变体,但到目前为止都导致了错误。
必须有一个简单的方法来做到这一点。
更新:
这是分组为 vi pd.TimeGrouper(3MS) 的数据帧。我想取列成本 1 的绝对值,然后计算平均值。
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()
但我得到了:
/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')
您可能会收到错误消息,因为您无法在 Sereis 对象上使用 .agg
。
您没有 post 您的分组对象,所以我不知道是否还有其他问题,但您应该以这种方式尝试。我认为这应该有效:
dct['x'] = grouped['profit'].mean() / grouped['cost'].abs().mean()
根据您的更新,我认为您正在寻找对组的绝对值取一个平均值。
使用 grouped.apply(abs).mean()
会将 abs
函数应用于您组中的值(cost1
等),而 mean
将为您提供任何分组的平均值变量是。
也可以只在分组前应用abs
函数,然后直接使用mean
函数
我想计算分组对象的绝对值的平均值。
即
grouped = df.groupby([pd.TimeGrouper(3MS)])
dct['x'] = grouped['profit'].agg('mean') / grouped['cost'].abs().agg('mean')
但是,上面的代码会导致错误。我已经尝试了上述代码的各种变体,但到目前为止都导致了错误。
必须有一个简单的方法来做到这一点。
更新:
这是分组为 vi pd.TimeGrouper(3MS) 的数据帧。我想取列成本 1 的绝对值,然后计算平均值。
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()
但我得到了:
/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')
您可能会收到错误消息,因为您无法在 Sereis 对象上使用 .agg
。
您没有 post 您的分组对象,所以我不知道是否还有其他问题,但您应该以这种方式尝试。我认为这应该有效:
dct['x'] = grouped['profit'].mean() / grouped['cost'].abs().mean()
根据您的更新,我认为您正在寻找对组的绝对值取一个平均值。
使用 grouped.apply(abs).mean()
会将 abs
函数应用于您组中的值(cost1
等),而 mean
将为您提供任何分组的平均值变量是。
也可以只在分组前应用abs
函数,然后直接使用mean
函数