获取()Pandas系列中的默认值,使用位置

问题描述:

当按位置访问行时,Pandas有没有办法获得默认值?我知道.get()函数,但在按索引搜索时适用。获取()Pandas系列中的默认值,使用位置

下面是我想做的事情。数据框:

In [24]: df 
Out[24]: 
    col1 
idx 
20  A 
21  B 
22  C 
23  D 
24  E 

通过索引搜索和获取的默认值正常工作:

In [25]: df['col1'].get(23, 'the_default_value') 
Out[25]: 'D' 

In [26]: df['col1'].get(28, 'the_default_value') 
Out[26]: 'the_default_value' 

但似乎没有要通过位置搜索等效方式。我可以使用.iloc(),但如果该行不存在,它无法获取默认值。例如。

In [57]: df['col1'].iloc[2] 
Out[57]: 'C' 

In [58]: df['col1'].iloc[6] 
... 
IndexError: single positional indexer is out-of-bounds 

我可以将它设置使用try...except,或事先检查,如果该值存在与否,但有这样做的更清洁的方式,如.iget()(如.loc VS .iloc)?

+0

您可以重置索引,使其从“0”开始 – EdChum

+0

是的,这是可能的。但是如果我需要实际的索引,它将意味着来回重置索引(其中一个用途在循环内)。 – vk1011

会像这样更干净:

df['new_index'] = np.arange(df.shape[0]) 
df = df.set_index('new_index') 

df['col1'].get(2, 'the_default_value') 

如果需要原来的指标,那么,它可能是用多指标

df['new_index'] = np.arange(df.shape[0]) 
df = df.set_index('new_index', append=True) 

df['col1'].get((pd.IndexSlice[:], 2), 'the_default_value') 
+1

谢谢,但这看起来在可读性方面变得越来越复杂。我认为在你的第一个解决方案中,你还需要摆脱原来的索引才能工作 - 在这种情况下,只需执行'df.reset_index()'就可以了。但我试图避免改变索引。 – vk1011

好的有用的,我得到了另一个答案:

n = 2 
df['col1'].get(df.index[n] if n < df.shape[0] else None, 'hi') 

因此,使用获取位置值进入索引...