【问题标题】:AttributeError when using numpy.logical_and with Pandas Series object将 numpy.logical_and 与 Pandas Series 对象一起使用时出现 AttributeError
【发布时间】:2012-11-17 16:59:54
【问题描述】:

在使用reindex_like 和相关功能时,我对 Pandas 系列对象之间的区别感到困惑。例如,考虑以下 Series 对象:

>>> import numpy
>>> import pandas
>>> series = pandas.Series([1, 2, 3])
>>> x = pandas.Series([True]).reindex_like(series).fillna(True)
>>> y = pandas.Series(True, index=series.index)
>>> x
0    True
1    True
2    True
>>> y
0    True
1    True
2    True

表面上xy 的内容和索引似乎相同。但是,它们必须在某些方面有所不同,因为其中一个在使用 numpy.logical_and() 时会导致错误,而另一个则不会。

>>> numpy.logical_and(series, y)
0    True
1    True
2    True
>>> numpy.logical_and(series, x)
Traceback (most recent call last):
  File "<ipython-input-10-e2050a2015bf>", line 1, in <module>
    numpy.logical_and(series, x)
AttributeError: logical_and

numpy.logical() 在这里抱怨什么?我看不出xy 这两个系列之间的区别。但是,肯定有一些细微的差别。

Pandas 文档说 Series 对象是“大多数 NumPy 函数”的有效参数。显然,在这种情况下,这在某种程度上是正确的。显然,创建机制使 x 无法用于这个特定的 numpy 函数。

作为旁注,reindex_like()index 参数这两种创建机制中的哪一种在这种情况下更有效和更惯用?也许还有另一种/更好的方法我也没有考虑过。

【问题讨论】:

  • 您使用的是哪个 pandas/numpy/python 版本? numpy.logical_and(series, x)pandas-0.9.0-py2.7 中对我来说没有错误...
  • 使用 pandas 0.9.1 和 numpy 1.6.2
  • 如果这是 pandas 0.9.1 中的一个新错误,我会感到惊讶,但也许值得升级到 numpy 1.8 版? (我正在使用的版本似乎可以工作......)
  • numpy 的当前稳定版本是 1.6.2(通过 PyPi 和 numpy 站点)。您是否在 1.8 版中使用 numpy 的 github 存储库?我想我会为 pandas 发布一个 github 问题,看看他们怎么说。
  • 我在 github 上为 Pandas 发布了一个问题。也许他们会有更多的见解:github.com/pydata/pandas/issues/2388

标签: python numpy pandas


【解决方案1】:

看起来这不是一个错误,细微的差别是由于使用了reindex_like() 方法。对reindex_like() 的调用将一些NaN 数据插入到系列中,因此该系列的dtypebool 更改为object

>>> series = pandas.Series([1, 2, 3])
>>> x = pandas.Series([True])
>>> x.dtype
dtype('bool')
>>> x = pandas.Series([True]).reindex_like(series)
>>> x.dtype
dtype('object')

我在 Pandas github 页面上发布了关于此异常的 issue

完整的解释/讨论是here。看起来这种行为将来可能会改变,所以请关注issue 以了解更多正在进行的细节。

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2019-10-20
    • 2022-07-14
    • 2011-08-20
    相关资源
    最近更新 更多