0

Python experts,

Is there a way to get NaN if a name doesn't not exist in the index? Say I pass in a list to retrieve the data Series. Currently, if I do df[myindex] directly, for those names non-existent in the index, I will get errors like:

KeyError: "['SAL_YIELD_NTM'] not in index"

I'd like to get the normal results back but put Nan for those non-existent index names. Is there a way for this in Python?

Thanks much!

Nick
  • 138,499
  • 22
  • 57
  • 95
Jasper
  • 53
  • 2
  • Just check if the key exists on the data structure (list or dictionary). If it doesn't, just return `float("NaN")` to get the Not a Number value. By the way, it is already answered here how you can get / assign this value: https://stackoverflow.com/questions/5438745/is-it-possible-to-set-a-number-to-nan-or-infinity – Carl HR Jun 24 '22 at 01:17
  • 2
    Lots of ways, e.g. `df.get(myindex, float('NaN'))` – President James K. Polk Jun 24 '22 at 01:22

1 Answers1

0

You can try to get the key, and if an error is raised handle it however you want:

try:
    my_value = df[myindex]
except KeyError as e:
    my_value = "NaN"

If df is a dictionary, you can use the get method which can be provided with a default value if the key is not found:

my_value = df.get(myindex, "NaN")
Jabrove
  • 718
  • 5
  • 13