首页 > 解决方案 > 如何使用 pandas Series 和 python 解决 >ValueError<?

问题描述

我将python (3.7.4) 与pandas (0.25.0) 一起使用,并希望value_counts()在系列上使用。

在执行语句时,我得到一个ValueError

有什么建议可以解决这个错误吗?

import pandas as pd
series = pd.Series([1, 2], index=pd.DatetimeIndex(['2019-09-22', '2019-09-24']))
series.groupby(pd.Grouper(freq='D')).value_counts()

堆栈跟踪:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/site-packages/pandas/core/groupby/generic.py", line 1244, in value_counts
    labels = list(map(rep, self.grouper.recons_labels)) + [llab(lab, inc)]
  File "<__array_function__ internals>", line 6, in repeat
  File "/usr/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 481, in repeat
    return _wrapfunc(a, 'repeat', repeats, axis=axis)
  File "/usr/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 61, in _wrapfunc
    return bound(*args, **kwds)
ValueError: operands could not be broadcast together with shape (3,) (2,)

Python:

$ python3
Python 3.7.4 (default, Jul 16 2019, 07:12:58) 
[GCC 9.1.0] on linux

编辑

注意:给定的数据只是重现错误的测试数据。

由于某些原因,更改后的数据集可以正常工作:

import pandas as pd
series = pd.Series([1, 2], index=pd.DatetimeIndex(['2019-09-22', '2019-09-23']))
series.groupby(pd.Grouper(freq='D')).value_counts()
2019-09-22  1    1
2019-09-23  2    1
dtype: int64

标签: pythonpython-3.xpandasseries

解决方案


错误来自应用.value_counts()到使用Grouper.

您可以通过查看示例中的组来看到这一点:

for n,g in series.groupby(pd.Grouper(freq='D')):
    print(n,'\n', g, '\n')

2019-09-22 00:00:00
 2019-09-22    1
dtype: int64

2019-09-23 00:00:00
 Series([], dtype: int64)

2019-09-24 00:00:00
 2019-09-24    2
dtype: int64

为避免将空系列传递给.value_counts()方法,请.apply()在此答案中指出的 groupby 对象上使用:https ://stackoverflow.com/a/45805110/7517724 。

对于您的情况,代码应为:

import pandas as pd
series = pd.Series([1, 2], index=pd.DatetimeIndex(['2019-09-22', '2019-09-24']))
series.groupby(pd.Grouper(freq='D')).apply(lambda g: g.value_counts())

产生:

2019-09-22  1    1
2019-09-24  2    1
dtype: int64

.to_period()另一种选择是避免重新采样,而是使用DateTime 索引上的方法将索引转换为您感兴趣的时间段:

series.groupby(series.index.to_period(freq='D')).value_counts()

它产生与示例相同的输出.apply()


推荐阅读