Specify pandas index name in the constructor

Viewed 984

Can I specify a pandas DataFrame index name in the constructor?

Said otherwise, I would like to do the following:

df = pd.DataFrame({"a":[1,2],"b":[3,4]})
df.rename_axis(index='myindex', inplace=True)

with a single line of code (by calling only the constructor)

1 Answers

You can pass an index to the DataFrame constructor with the given name that you want.

import pandas as pd

df = pd.DataFrame({"a":[1,2],"b":[3,4]}, index=pd.Index([], name='myIndex'))
df
>>>
    a   b
myIndex     
0   1   3
1   2   4
Related