SoFunction
Updated on 2024-11-19

Example of two ways for Pandas to modify the names of DataFrame columns

Input:

   $a  $b  $c  $d  $e
0   1   2   3   4   5

Desired Output:

   a  b  c  d  e
0  1  2  3  4  5

The original data DataFrame:

import pandas as pd
 
df = ({'$a': [1], '$b': [2], '$c': [3], '$d': [4], '$e': [5]})

Solution 1: Modification through the class's own attributes

1. Violent modifications

 = ['a', 'b', 'c', 'd', 'e']

2. The stirp method

The strip() method is used to remove the specified characters (spaces or newlines by default) or sequence of characters at the beginning and end of a string.

 = ('$')

3. lambda expressions

map() maps the specified sequence according to the provided function. Calls the function function with each element of the argument sequence, returning a new list of the values returned by each function function.

lambda x: x[1:] means to take the second element, so the list names $a, $b, etc. take out only a and b.

 = (lambda x: x[1:])

Solution 2: Modify by () function

1. Violent modification (only part of the column name can be modified)

(columns=('$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True) 

2. lambda expressions

Call the replace function to replace $ with null.

(columns=lambda x:('$',''), inplace=True)

pandas Example of changing the row or column name of a DataFrame

To change the name of a row or column, you can use the rename function.

First, construct a dataframe:

import pandas as pd
d={'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}}
df=(d)
print(df)
1
2
3
4

The output result is:

one two three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12

Change column name

Change the name of column 2 to twotwo

(columns={'two':'twotwo'},inplace=True)
print(df)
1
2

The output result is:

one twotwo three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12

Changing Line Names

Change the row names in rows 1 and 2 to aa,bb

(index={'a':'aa','b':'bb'},inplace=True)
print(df)
1
2

The output result is:

one twotwo three
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12

The change was successful.

Of course, there is also the option of violently changing row or column names:

=['onon','twtw','thth']
print(df)
1
2

The output result is:

onon twtw thth
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12

summarize

to this article on Pandas to modify the DataFrame column name of the two methods are introduced to this article, more related to Pandas to modify the DataFrame column name content, please search for my previous posts or continue to browse the following articles hope that you will support me in the future more!