Specify pandas index name in the constructor
Asked Answered
A

2

12

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)

Ablative answered 30/11, 2020 at 23:8 Comment(2)
Chain the rename_axis without inplace to the constructor?Poultryman
Why not chain the two, so df = pd.DataFrame({"a":[1,2],"b":[3,4]}).rename_axis(index='myindex').Lytton
D
13

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
Doncaster answered 30/11, 2020 at 23:34 Comment(2)
I am receiving an error ValueError: Shape of passed values is (2, 2), indices imply (0, 2).Ursal
I'm getting ValueError: Length of values (2) does not match length of index (0). And for a series with existing indices, pd.Series({"a": 1, "b": 3}, index=pd.Index([], name='myIndex')), the result is empty: Series([], dtype: int64)Camboose
C
0

The closest you can get is inlining the .rename_axis call:

pd.DataFrame({"a": [1, 2], "b": [3, 4]}).rename_axis('myindex')
         a  b
myindex
0        1  3
1        2  4
Camboose answered 31/3 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.