2017-09-23 178 views
0

所以我读了一个29列的数据表,我在一个索引列中添加(总共30个)。Python pandas.core.indexing.IndexingError:不可对齐的布尔系列键提供

Data = pd.read_excel(os.path.join(BaseDir, 'test.xlsx')) 
Data.reset_index(inplace=True) 

然后,我想子集的数据只包括列名称包含“ref”或“Ref”的列;我下面的代码从另一个叠后:

col_keep = Data.ix[:, pd.Series(Data.columns.values).str.contains('ref', case=False)] 

不过,我不断收到此错误:

print(len(Data.columns.values)) 
    30 
    print(pd.Series(Data.columns.values).str.contains('ref', case=False)) 
    0  False 
    1  False 
    2  False 
    3  False 
    4  False 
    5  False 
    6  False 
    7  False 
    8  False 
    9  False 
    10 False 
    11 False 
    12 False 
    13 False 
    14 False 
    15 False 
    16 False 
    17 False 
    18 False 
    19 False 
    20 False 
    21 False 
    22 False 
    23 False 
    24  True 
    25  True 
    26  True 
    27  True 
    28 False 
    29 False 
    dtype: bool 

Traceback (most recent call last): 
    File "C:/Users/lala.py", line 26, in <module> 
    col_keep = FedexData.ix[:, pd.Series(FedexData.columns.values).str.contains('ref', case=False)] 
    File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexing.py", line 84, in __getitem__ 
    return self._getitem_tuple(key) 
    File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexing.py", line 816, in _getitem_tuple 
    retval = getattr(retval, self.name)._getitem_axis(key, axis=i) 
    File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexing.py", line 1014, in _getitem_axis 
    return self._getitem_iterable(key, axis=axis) 
    File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexing.py", line 1041, in _getitem_iterable 
    key = check_bool_indexer(labels, key) 
    File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexing.py", line 1817, in check_bool_indexer 
    raise IndexingError('Unalignable boolean Series key provided') 
pandas.core.indexing.IndexingError: Unalignable boolean Series key provided 

所以布尔值是正确的,但它为什么不工作?为什么错误不断弹出?

任何帮助/提示表示赞赏!非常感谢你。

回答

0

我可以重现类似的错误消息是这样的:

import numpy as np 
import pandas as pd 

df = pd.DataFrame(np.random.randint(4, size=(10,4)), columns=list('ABCD')) 
df.ix[:, pd.Series([True,False,True,False])] 

加薪(使用熊猫版0.21.0.dev + 25.g50e95e0)

pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match 

出现该问题,因为大熊猫是试图在使用系列布尔值 值进行掩码前,将 系列的索引与DataFrame的列索引对齐。由于df有列标志'A', 'B', 'C', 'D'和系列具有 的索引标识0123,大熊猫是抱怨说,标签是 unalignable。

你可能不希望任何索引对齐。所以相反,通过一个NumPy的布尔数组而不是熊猫系列:

mask = pd.Series(Data.columns.values).str.contains('ref', case=False).values 
col_keep = Data.loc[:, mask] 

Series.values属性返回NumPy的阵列。并且由于在未来版本的熊猫中,DataFrame.ix will be removed,请使用Data.loc而不是Data.ix,因为我们需要布尔索引。

+0

非常感谢你!它工作得很好:) – alwaysaskingquestions