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"
akshat
  • 1,219
  • 1
  • 8
  • 24
acneyouth
  • 111
  • 1
  • 4
  • 1
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael May 16 '18 at 06:11
  • how working `datevar['2000-01-01']` ? – jezrael May 16 '18 at 06:13

1 Answers1

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
lihua
  • 21
  • 1