python: pandas.DataFrame,how to avoid keyerror?

In C++, when I can't find a keyword in a table, it will return NULL or in database it will return a empty table, so the program continues to run. But in python, it throws an exception, and interrupts my program. Can I avoid that? for example, I have such a DataFrame named 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"

1 answer

  • answered 2018-05-16 08:00 lihua

    I think you can check if the index is existed in the df's index or the columns before you get the value of that key.

    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