2016-07-08 32 views
1

當按位置訪問行時,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

回答

0

會像這樣更乾淨:

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

0

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

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

因此,使用獲取位置值進入索引...