Richard Richard - 3 months ago 269
Python Question

Is there a way to look up by index value without handling errors?

I have a dataframe that looks like this:

pmid
id
NCT02835976 NaN
NCT02835885 1235
NCT02835560 1270
NCT02835118 NaN


Now I want to find the row that matches a particular key. I can do
df.loc(x)
but I get an error if the ID is not in the index:

KeyError: u'the label [NCT01001741] is not in the [index]'


Do I really need to write error-handling code? Is there any method in pandas that will simply return
None
if the key is not in the index?

The docs seem to suggest that
ix
will do this, but also that
ix
is generally to be avoided.

Answer

You can try something like following:

df[df.index == 'NCT01001741']

This will return no error

Comments