2012-11-29 14 views
0

我對使用reindex_like和相關功能時Pandas系列對象之間的差異感到困惑。例如,請考慮以下系列對象:使用numpy.logical_and和Pandas系列對象時出現AttributeError

>>> 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之間的區別。但是,必須有一些細微的差別。

熊貓文檔說明Series對象是「大多數NumPy函數」的有效參數。很顯然,在這種情況下,情況確實如此。顯然創建機制使得x對這個特定的numpy函數不可用。

作爲一個側面說明,兩種創建機制中的哪一種,reindex_like()index參數對於這種情況更爲有效和習慣?也許還有另外一種/更好的方式我也沒有考慮過。

+0

你使用哪個pandas/numpy/python版本? 'numpy.logical_and(series,x)'在'pandas-0.9.0-py2.7'中對我沒有任何錯誤... –

+0

使用熊貓0.9.1和numpy 1.6.2 –

+0

如果這是一個熊貓0.9.1的新bug,但可能值得升級到numpy 1.8版本? (我使用的版本似乎工作...) –

回答

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') 

我發佈了一個issue關於熊貓github頁面上的這個異常。

完整的解釋/討論是here。看起來這種行爲在未來可能會發生變化,所以請查看issue瞭解更多正在進行的細節。

相關問題