python:pandas.DataFrame?如何避免keyerror?

acn*_*uth 6 python dataframe pandas keyerror

C++,当我在表中找不到关键字时,它将返回NULL或在数据库中它将返回一个空表,因此程序继续运行。但是在 中python,它会抛出一个exception,并中断我的程序。我可以避免吗?例如,我有一个名为的 DataFrame datevar

(datetimeIndex)   value
2001-01-01           1
2001-01-02           1
2001-01-03           3
....

v = datevar.xs('2000-01-01', level='date') # of course "keyError"
v = datevar.loc['2000-01-01' , :]          # of course "keyError"
Run Code Online (Sandbox Code Playgroud)

小智 5

我认为您可以在获取该键的值之前检查该索引是否存在于 df 的索引或列中。

df = pd.read_clipboard()
df
Out[6]: 
  (datetimeIndex)  value
0      2001-01-01      1
1      2001-01-02      1
2      2001-01-03      3
key = "2000-01-01"
if key in df.index:
    v = df.xs('2000-01-01', level='date')  # of course "keyError"
    v = df.loc['2000-01-01', :]  # of course "keyError"
else:
    v = None
v
Run Code Online (Sandbox Code Playgroud)