Tag Archives: DataFrame.rename

Methods of modifying index and columns names by dataframe in pandas

Dataframe.index = [newName], dataframe.columns = [newName]. Dataframe.columns = [newName].
, use the rename method (recommended) :
dataframe.rename (mapper = None, index = None, axis = None, copy = True, inplace = False, level = None)
mapper, index, level = None) You can use any of them, such as combining index and Columns. Index and column are passed directly into mapper or dictionary form.
axis: int or STR, used with mapper. These can be axis names (‘ index ‘, ‘columns’) or Numbers (0,1). The default is’ index ‘.
copy: Boolean, which defaults to True, whether to copy the underlying data.
inplace: Boolean value, default to False, whether to return a new DataFrame. If True, the copy value is ignored.

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

df1 = DataFrame(np.arange(9).reshape(3, 3), index = ['bj', 'sh', 'gz'], columns=['a', 'b', 'c'])
print(df1)
'''
    a  b  c
bj  0  1  2
sh  3  4  5
gz  6  7  8
'''

# Modify the index of df1
print(df1.index) # You can print out the print value and also assign a value to it.
df1.index = Series(['beijing', 'shanghai', 'guangzhou'])
print(df1)
'''
           a  b  c
beijing    0  1  2
shanghai   3  4  5
guangzhou  6  7  8
'''

# You can use the map method for mapping, which is almost identical to the map in python.
print(df1.index.map(str.upper)) # Index(['BEIJING', 'SHANGHAI', 'GUANGZHOU'], dtype='object')

print(df1) # The result does not change, it just returns a dataframe instead.
'''
           a  b  c
beijing    0  1  2
shanghai   3  4  5
guangzhou  6  7  8
'''

# If it needs to be changed, it can be as follows: Assign another value to a variable
df1.index = df1.index.map(str.upper)
print(df1) # This changes the
'''
           a  b  c
BEIJING    0  1  2
SHANGHAI   3  4  5
GUANGZHOU  6  7  8
'''

# A faster method uses rename, which you can specify values for index and column respectively.
# Assign a value using the map method
df2 = df1.rename(index=str.lower, columns=str.upper) # This method also generates a new dataframe
print(df2)
''' can be easily modified. dataframe 的 index 和 columns
           A  B  C
beijing    0  1  2
shanghai   3  4  5
guangzhou  6  7  8
'''

# At the same time, rename can also be passed into the dictionary
df3 = df2.rename(index={'beijing':'bj'}, columns = {'A':'aa'}) # Change the name for an index separately
print(df3) #
'''
           aa  B  C
bj          0  1  2
shanghai    3  4  5
guangzhou   6  7  8
'''

# Custom map functions
def test_map(x):
    return x+'_ABC'

print(df1.index.map(test_map))
# output Index(['BEIJING_ABC', 'SHANGHAI_ABC', 'GUANGZHOU_ABC'], dtype='object')

print(df1.rename(index=test_map))
'''
               a  b  c
BEIJING_ABC    0  1  2
SHANGHAI_ABC   3  4  5
GUANGZHOU_ABC  6  7  8
'''