Q:

python how to rename columns in pandas dataframe

# Basic syntax:
# Assign column names to a Pandas dataframe:
pandas_dataframe.columns = ['list', 'of', 'column', 'names']
# Note, the list of column names must equal the number of columns in the
# 	dataframe and order matters

# Rename specific column names of a Pandas dataframe:
pandas_dataframe.rename(columns={'name_to_change':'new_name'})
# Note, with this approach, you can specify just the names you want to
# 	change and the order doesn't matter
5
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(columns={"A": "a", "B": "c"})
   a  c
0  1  4
1  2  5
2  3  6
3
df.rename(columns={"old_col1": "new_col1", "old_col2": "new_col2"})
12
df.rename(columns={'oldName1': 'newName1',
                   'oldName2': 'newName2'},
          inplace=True, errors='raise')
# Make sure you set inplace to True if you want the change
# to be applied to the dataframe
15
df.rename(columns={"old_col1": "new_col1", "old_col2": "new_col2"}, inplace=True)
7
import pandas as pd
data = pd.read_csv(file)
data.rename(columns={'original':'new_name'}, inplace=True)
5
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) 
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
1
df_new = df.rename(columns={'A': 'a'}, index={'ONE': 'one'})
print(df_new)
#         a   B   C
# one    11  12  13
# TWO    21  22  23
# THREE  31  32  33

print(df)
#         A   B   C
# ONE    11  12  13
# TWO    21  22  23
# THREE  31  32  33
1
>>> df.rename(index={0: "x", 1: "y", 2: "z"})
   A  B
x  1  4
y  2  5
z  3  6
2

New to Communities?

Join the community