DataFrame中基于标签的安全选择

时间:2016-10-23 15:58:14

标签: python pandas

如何通过标签列表安全地选择pandas中的行?
当列表包含任何不存在的标签时,我想得到Error

如果您要求的标签中至少有一个位于索引中,则方法loc不会引发KeyError。但这还不够。

例如:

df = pd.DataFrame(index=list('abcde'), data={'A': np.arange(5) + 10})

df
    A
a  10
b  11
c  12
d  13
e  14

# here I would like to get an Error as 'xx' and 'yy' are not in the index
df.loc[['b', 'xx', 'yy']] 

       A
b   11.0
xx   NaN
yy   NaN

pandas是否提供了这样一种方法,它会引发KeyError而不是为不存在的标签返回一堆 NaNs

3 个答案:

答案 0 :(得分:2)

这有点像黑客,但人们可以这样做:

def my_loc(df, idx):
    assert len(df.index[df.index.isin(idx)]) == len(idx), 'KeyError:the labels [{}] are not in the [index]'.format(idx)
    return df.loc[idx]

In [243]: my_loc(df, idx)
...
skipped
...
AssertionError: KeyError:the labels [['b', 'xx', 'yy']] are not in the [index]

In [245]: my_loc(df, ['a','c','e'])
Out[245]:
    A
a  10
c  12
e  14

答案 1 :(得分:1)

我认为您获得NaN因为locix返回与reindex相同的输出。请参阅reindex versus ix

从开放式issue 10695中选择“安全”的解决方案:

list_of_values = ['b', 'xx', 'yy']
print (df.ix[df.reset_index()['index'].isin(list_of_values).values])
    A
b  11

如果值不在index中,则返回错误的一种解决方案是使用drop

df.drop(list_of_values)
print (df.loc[list_of_values])
  

ValueError:标签['xx''yy']未包含在轴

答案 2 :(得分:1)

.loc[]如果列表中的索引不属于初始df

,则不允许您设置值

所以你可以这样做:

df = pd.DataFrame(index=['a','b','c','d', 'e'], data={'A':range(5)})
index_list = ['a', 'b']
df.loc[index_list] = df.loc[index_list]
df.loc[index_list]
Out[288]: 
   A
a  0
b  1

现在让我们测试虚拟索引:

index_list = ['aa', 'b']
df.loc[index_list] = df.loc[index_list]

您将收到此错误

   Traceback (most recent call last):
      File "C:\Anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-289-d6aac5dac03d>", line 2, in <module>
        df.loc[index_list] = df.loc[index_list]
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 139, in __setitem__
        indexer = self._get_setitem_indexer(key)
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 126, in _get_setitem_indexer
        return self._convert_to_indexer(key, is_setter=True)
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1229, in _convert_to_indexer
        raise KeyError('%s not in index' % objarr[mask])
    KeyError: "['aa'] not in index"