get() 用于 Pandas 系列中的默认值,使用位置

vk1*_*011 9 python pandas

当按位置访问一行时,Pandas 有没有办法获得默认值?我知道该.get()功能,但在按索引搜索时有效。

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

In [24]: df
Out[24]:
    col1
idx
20     A
21     B
22     C
23     D
24     E
Run Code Online (Sandbox Code Playgroud)

按索引搜索并获取默认值工作正常:

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'
Run Code Online (Sandbox Code Playgroud)

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

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

In [58]: df['col1'].iloc[6]
...
IndexError: single positional indexer is out-of-bounds
Run Code Online (Sandbox Code Playgroud)

我可以使用 来设置它try...except,或者事先检查该值是否存在,但是有没有更简洁的方法,比如.iget()(比如.locvs .iloc)?

Ger*_*ges 2

像这样的东西会被认为更干净吗:

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

df['col1'].get(2, 'the_default_value')
Run Code Online (Sandbox Code Playgroud)

如果需要原始索引,那么,使用多索引可能会很有用

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')
Run Code Online (Sandbox Code Playgroud)