9

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"
2

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Like dict has get method there should be some method which doesn't hurt and halt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.