Home > Backend Development > Python Tutorial > How Can I Rename Columns in a Pandas DataFrame?

How Can I Rename Columns in a Pandas DataFrame?

Mary-Kate Olsen
Release: 2024-12-20 13:47:09
Original
201 people have browsed it

How Can I Rename Columns in a Pandas DataFrame?

Renaming Column Names in Pandas

To change the column labels of a Pandas DataFrame, a number of methods are available.

Rename Specific Columns

Use the df.rename() function to specify the columns to be renamed:

df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})

# Or rename the existing DataFrame
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
Copy after login

Reassign Column Headers

Use df.set_axis() with axis=1 to reassign the column headers:

df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1)
Copy after login

Headers can also be assigned directly:

df.columns = ['V', 'W', 'X', 'Y', 'Z']
Copy after login

Minimal Code Example

To rename the columns of a DataFrame from ['a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']:

import pandas as pd

df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df2 = df.rename(columns={'$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'})

print(df2)
Copy after login

Output:

   a  b  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x
Copy after login

The above is the detailed content of How Can I Rename Columns in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template