Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between index.name and index.names in pandas

I have just started leaning pandas and this is really my first question here so pls don't mind if its too basic !

When to use df.index.name and when df.index.names ? Would really appreciate to know the difference and application.

Many Thanks

like image 232
blg Avatar asked Oct 25 '25 02:10

blg


1 Answers

name returns the name of the Index or MultiIndex.
names returns a list of the level names of an Index (just one level) or a MultiIndex (more than one level).

Index:

df1 = pd.DataFrame(columns=['a', 'b', 'c']).set_index('a')
print(df1.index.name, df1.index.names)
# a ['a']

MultiIndex:

df2 = pd.DataFrame(columns=['a', 'b', 'c']).set_index(['a', 'b'])
print(df2.index.name, df2.index.names)
# None ['a', 'b']

df2.index.name = 'my_multiindex'
print(df2.index.name, df2.index.names)
# my_multiindex ['a', 'b']
like image 160
Stef Avatar answered Oct 27 '25 21:10

Stef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!