使用numpy.logical_and和Pandas Series对象时的AttributeError

时间:2012-11-29 15:15:16

标签: python numpy pandas

在使用reindex_like和相关功能时,我对Pandas Series对象之间的区别感到困惑。例如,请考虑以下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参数对于这种情况更有效和惯用?也许还有另一种/更好的方式我也没有考虑过。

1 个答案:

答案 0 :(得分:0)

看起来这不是一个错误,而细微的差异是由于使用了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以获取更多正在进行的详细信息。