Skip to content
Advertisement

How to add column name for index in Pandas dataframe

This is about Pandas dataframe. I have a dataframe made by following python code.

df_test = pd.DataFrame(np.arange(12).reshape(3, 4),
columns=['col_0', 'col_1', 'col_2', 'col_3'],
index=['row_0', 'row_1', 'row_2'])

There is no column name for index. What I’d like to do is adding index’s name like ‘date’ in attached capture.

enter image description here

I did following, but error occurred because there is no such name of column in df_test. I know that, so I want to add it.

df_test.set_index('date', inplace=True)

KeyError: “None of [‘date’] are in the columns”

Is there any way to add ‘date’ to existed dataframe df_test?

Thank you in advance.

Advertisement

Answer

You have already added date as column. So you have to either add new name to index or reset the index.

Advertisement