【问题标题】:How to sovle >ValueError< with pandas Series and python?如何使用 pandas Series 和 python 解决 >ValueError<?
【发布时间】:2020-01-22 18:44:59
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: python python-3.x pandas series


    【解决方案1】:

    错误是由于将.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() 方法,请在 groupby 对象上使用 .apply(),如此答案中所指出的: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
    

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

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

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

    【讨论】:

      【解决方案2】:

      如果您尝试访问 series.groupby(pd.Grouper(freq='D')) 的值,您将不会得到一个 Series,而是一个 SeriesGroupBy 对象。

      试试这个:series.groupby(pd.Grouper(freq='D')).first().value_counts()

      【讨论】:

        猜你喜欢
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 2019-08-03
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2016-05-10
        相关资源
        最近更新 更多