python - 如何在具有 Decimal 类型值的 pandas TimeSeries 上使用 mean 方法?

标签 python decimal dataframe pandas

我需要将 Python 十进制类型值存储在 pandas TimeSeries/DataFrame 对象中。在 TimeSeries/DataFrame 上使用“groupby”和“mean”时,Pandas 给我一个错误。以下基于 float 的代码运行良好:

[0]: by = lambda x: lambda y: getattr(y, x)

[1]: rng = date_range('1/1/2000', periods=40, freq='4h')

[2]: rnd = np.random.randn(len(rng))

[3]: ts = TimeSeries(rnd, index=rng)

[4]: ts.groupby([by('year'), by('month'), by('day')]).mean()
2000  1  1    0.512422
         2    0.447235
         3    0.290151
         4   -0.227240
         5    0.078815
         6    0.396150
         7   -0.507316

但是如果使用十进制值而不是 float 来做同样的事情,我会得到一个错误:

[5]: rnd = [Decimal(x) for x in rnd]       

[6]: ts = TimeSeries(rnd, index=rng, dtype=Decimal)

[7]: ts.groupby([by('year'), by('month'), by('day')]).mean()  #Crash!

Traceback (most recent call last):
File "C:\Users\TM\Documents\Python\tm.py", line 100, in <module>
print ts.groupby([by('year'), by('month'), by('day')]).mean()
File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 293, in mean
return self._cython_agg_general('mean')
File "C:\Python27\lib\site-packages\pandas\core\groupby.py", line 365, in _cython_agg_general
raise GroupByError('No numeric types to aggregate')
pandas.core.groupby.GroupByError: No numeric types to aggregate

错误信息是“GroupByError('No numeric types to aggregate')”。是否有机会在包含 Decimal 值的 TimeSeries 或 DataFrame 上使用标准聚合,如 sum、mean 和 quantileon?

为什么它不起作用?如果不可能,是否有机会找到同样快速的替代方案?

编辑:我刚刚意识到大多数其他函数(最小值、最大值、中值等)工作正常,但不是我迫切需要的平均函数:-(。

最佳答案

import numpy as np
ts.groupby([by('year'), by('month'), by('day')]).apply(np.mean)

关于python - 如何在具有 Decimal 类型值的 pandas TimeSeries 上使用 mean 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459106/

相关文章:

Python mysql动态添加列并更新新列中的值

python - 关闭 R Notebook 中的警告

java - 如何将 int 数从十进制转换为二进制?

python - 如何使用 pandas df.plot.scatter 制作带有子图的图形

python - 尝试从 GAE 动态提供图像,得到 404

python - 将 python3 设为我在 Mac 上的默认 python

perl - 大数的十进制和二进制转换

html - 如何在 Foundation 6 中接受 Decimal 值

R - 具有来自另一个数据帧的序列的数据帧

python - 使用 for 循环在数据框中添加值