當按位置訪問行時,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」開始 – EdChum
是的,這是可能的。但是如果我需要實際的索引,它將意味着來回重置索引(其中一個用途在循環內)。 – vk1011