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
Mary-Kate OlsenOriginal
2024-12-20 13:47:09202browse

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)

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)

Headers can also be assigned directly:

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

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)

Output:

   a  b  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

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!

Statement:
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