Several ways to modify the column names of dataframe in python

Project github address: bitcarmanlee easy-algorithm-interview-and-practice
often have students private messages or leave messages to ask related questions, V number bitcarmanlee. The classmates of star on github, within the scope of my ability and time, I will try my best to help you answer related questions and make progress together.

In actual development, there is often a need to modify the column name of the dataframe, and the following methods are specifically summarized.

import pandas as pd


def t1():
    df = pd.DataFrame({'c1':[1, 2, 3], 'c2': [4, 5, 6]})
    print(df)

    df.columns = ['d1', 'd2']
    print(df)

    df.rename(columns={'d1': 'e1', 'd2': 'e2'}, inplace=True)
    print(df)

    df = df.rename(columns={'e1': 'f1', 'e2': 'f2'})
    print(df)


t1()

The output of the above code:

   c1  c2
0   1   4
1   2   5
2   3   6
   d1  d2
0   1   4
1   2   5
2   3   6
   e1  e2
0   1   4
1   2   5
2   3   6
   f1  f2
0   1   4
1   2   5
2   3   6

As can be seen from the above code, there are two ways to modify the column names:
1. Rename directly using df.columns, but this method needs to list all column names.
2. Use the rename method. Note that if you need to modify it in place, you need to bring the parameter inplace=True, otherwise the original dataframe column name will not change.

Guess you like

Origin blog.csdn.net/bitcarmanlee/article/details/113109691