DataFram中基于标签的安全选择

2024-04-23 18:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过标签列表安全地选择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是否提供了这样一种方法来引发一个键错误,而不是为不存在的标签返回一堆nan?在


Tags: 方法dataframepandasdf列表indexerror标签
3条回答

这有点麻烦,但你可以这样做:

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

我认为您得到NaN,因为loc或{}返回与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中,返回错误的一个解决方案是使用^{}

^{pr2}$

ValueError: labels ['xx' 'yy'] not contained in axis

如果列表中的索引不是初始df的一部分,.loc[]将不允许您设置值

所以你可以做一些类似的事情:

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

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

^{pr2}$

你会得到这个错误

   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"

相关问题 更多 >