Rename Pandas Dataframe Index

Rename Pandas DataFrame Index

The rename method takes a dictionary for the index which applies to index values.

You want to rename to index level's name:

df.index.names = ['Date']

A good way to think about this is that columns and index are the same type of object (Index or MultiIndex), and you can interchange the two via transpose.

This is a little bit confusing since the index names have a similar meaning to columns, so here are some more examples:

In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))

In [2]: df
Out[2]:
A B C
0 1 2 3
1 4 5 6

In [3]: df1 = df.set_index('A')

In [4]: df1
Out[4]:
B C
A
1 2 3
4 5 6

You can see the rename on the index, which can change the value 1:

In [5]: df1.rename(index={1: 'a'})
Out[5]:
B C
A
a 2 3
4 5 6

In [6]: df1.rename(columns={'B': 'BB'})
Out[6]:
BB C
A
1 2 3
4 5 6

Whilst renaming the level names:

In [7]: df1.index.names = ['index']
df1.columns.names = ['column']

Note: this attribute is just a list, and you could do the renaming as a list comprehension/map.

In [8]: df1
Out[8]:
column B C
index
1 2 3
4 5 6

Pandas rename index

You need to remove the column name:

df.rename_axis(None, axis=1).rename_axis('id', axis=0)
##if pd.__version__ == 0.24.0
#df.rename_axis([None], axis=1).rename_axis('id')

The problem is that 'summary' is your column name. When there is no index name, the column name is placed directly above the index, which can be misleading:

import pandas as pd
df = pd.DataFrame([[1]*2]*4, columns=['A', 'B'])
df.columns.name = 'col_name'
print(df)

#col_name A B
#0 1 1
#1 1 1
#2 1 1
#3 1 1

When you then try to add an index name, it becomes clear that 'col_name' was really the column name.

df.index.name = 'idx_name'
print(df)

#col_name A B
#idx_name
#0 1 1
#1 1 1
#2 1 1
#3 1 1

There is no ambiguity though: when you have an index name, the columns are raised one level, which allows you to distinguish between an index name and a column name.

df = pd.DataFrame([[1]*2]*4, columns=['A', 'B'])
df.index.name = 'idx_name'
print(df)

# A B
#idx_name
#0 1 1
#1 1 1
#2 1 1
#3 1 1

Pandas index column title or name

You can just get/set the index via its name property

In [7]: df.index.name
Out[7]: 'Index Title'

In [8]: df.index.name = 'foo'

In [9]: df.index.name
Out[9]: 'foo'

In [10]: df
Out[10]:
Column 1
foo
Apples 1
Oranges 2
Puppies 3
Ducks 4

How can I change the Index name using python pandas?

if you want to change in place

result.index.rename('Continent', inplace=True)

of assign new dataframe to existing:

result = result.index.rename('Continent')

Change index of a pandas data frame

You can use rename_axis:

DF.rename_axis('TestName').reset_index().set_index('b')

Renaming column names in Pandas

Just assign it to the .columns attribute:

>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20

>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20


Related Topics



Leave a reply



Submit