我利用類似於布爾系列試圖索引數據幀到hereIndexingError使用布爾索引
In [1]: import pandas as pd
In [2]: idx = pd.Index(["USD.CAD", "AUD.NZD", "EUR.USD", "GBP.USD"],
...: name="Currency Pair")
In [3]: pairs = pd.DataFrame({"mean":[3.6,5.1,3.6,2.7], "count":[1,5,8,2]}, index=idx)
In [4]: mask = pairs.reset_index().loc[:,"Currency Pair"].str.contains("USD")
In [5]: pairs.reset_index()[mask]
Out[5]:
Currency Pair count mean
0 USD.CAD 1 3.6
2 EUR.USD 8 3.6
3 GBP.USD 2 2.7
上述工作,當我嘗試用無索引重置我得到以下錯誤的原始數據幀
In [6]: pairs[mask]
C:\Anaconda\lib\site-packages\pandas\core\frame.py:1808: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
"DataFrame index.", UserWarning)
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
<ipython-input-6-9eca5ffbdaf7> in <module>()
----> 1 pairs[mask]
C:\Anaconda\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
1772 if isinstance(key, (Series, np.ndarray, Index, list)):
1773 # either boolean or fancy integer index
-> 1774 return self._getitem_array(key)
1775 elif isinstance(key, DataFrame):
1776 return self._getitem_frame(key)
C:\Anaconda\lib\site-packages\pandas\core\frame.pyc in _getitem_array(self, key)
1812 # _check_bool_indexer will throw exception if Series key cannot
1813 # be reindexed to match DataFrame rows
-> 1814 key = _check_bool_indexer(self.index, key)
1815 indexer = key.nonzero()[0]
1816 return self.take(indexer, axis=0, convert=False)
C:\Anaconda\lib\site-packages\pandas\core\indexing.pyc in _check_bool_indexer(ax, key)
1637 mask = com.isnull(result.values)
1638 if mask.any():
-> 1639 raise IndexingError('Unalignable boolean Series key provided')
1640
1641 result = result.astype(bool).values
IndexingError: Unalignable boolean Series key provided
我對這個錯誤很困惑,因爲我的印象是,這是如果布爾指數長度從數據幀的差異收到一個錯誤?以下情況並非如此。
In [7]: len(mask)
Out[7]: 4
In [8]: len(pairs)
Out[8]: 4
In [9]: len(pairs.reset_index())
Out[9]: 4
我認爲你在這裏有點困惑,你需要重置索引的原因是因爲如果你沒有,那麼將不會有任何匹配的掩碼索引值對作爲對df使用您的currency.pair字符串作爲指數值。在這種情況下,長度不是問題,這是事實上,索引值不能與你的掩碼索引吻合 – EdChum 2014-11-24 19:58:12
我不是一個熊貓專家,但它不是簡單地從原始'對'具有不同於' pairs.reset_index()'? 'pairs''索引具有'dtype = object',而'mask'具有'type = int64' – hopla 2014-11-24 20:03:11