Home > Software engineering >  Key error when trying to get a value in a Pandas Dataframe
Key error when trying to get a value in a Pandas Dataframe

Time:12-15

I have a pandas dataframe df that has a column with the name "datetime". Now I would like to get a specific value from it. I tried the solutions suggested here enter image description here

And here is what I tried:

print("df.at[5,'datetime']", df.at[5,"datetime"])
print("df.iloc['datetime', 5]", df.iloc[5]["datetime"])

Any idea, why I get this error and how to fix this problem?

CodePudding user response:

It looks like datetime is your index column so you should be able to access it through df.index[5]

If you want datetime to be a column like any other you can use df.reset_index().

If you want datetime to be a column but also keep it as your index use:

df['datetime'] = df.index

More generally:

df[df.index.name] = df.index

If you need an expression rather than a statement:

df.assign(**{df.index.name: df.index})
  • Related