Skip to content
Advertisement

Make Pandas `df.get()` behave gracefully whether column or row key is incorrect

I have a Pandas dataframe and a function that pulls entries from the dataframe. If the requested entry is not present in the dataframe—whether because the requested column does not exist, because the requested row/index does not exist, or both—I would like to return the string 'entry not found' instead of an error message.

JavaScript

Ideally, I would like to write my query function as

JavaScript

Unfortunately, the df.get() method only accepts two arguments, so I came up with the following alternatives.

JavaScript

Only query2 and query4 work if the user asks for a row that doesn’t exist:

JavaScript

Whereas only query3 (kind of) works if the user asks for a column that doesn’t exist:

JavaScript

How can I obtain the desired behavior? Is there a way to do this without a heavy try: ... except: ... block?

Advertisement

Answer

What about using get twice:

JavaScript

First get will look for a col column:

  • if it exists, then it gives df.col
  • if it doesn’t, then it gives a dict {} (so the successor get can work)

Then second get looks for idx row:

  • if df.col is queried with this, essentially returns df.loc[idx, col] if it exists
  • otherwise entry is not found
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement