0

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 How to get a value from a cell of a dataframe? but I always get an "KeyError: 'datetime'"

Here is a screenshot of the dataframe 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?

PeterBe
  • 700
  • 1
  • 17
  • 37

1 Answers1

1

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})
rudolfovic
  • 3,163
  • 2
  • 14
  • 38