0 votes
in Python Pandas by
How to Rename the Index or Columns of a Pandas DataFrame?

1 Answer

0 votes
by
You can use the .rename method to give different values to the columns or the index values of DataFrame.

There are the following ways to change index / columns names (labels) of pandas.DataFrame.

Use pandas.DataFrame.rename()

Change any index / columns names individually with dict

Change all index / columns names with a function

Use pandas.DataFrame.add_prefix(), pandas.DataFrame.add_suffix()

Add prefix and suffix to columns name

Update the index / columns attributes of pandas.DataFrame

Replace all index / columns names

set_index() method that sets an existing column as an index is also provided. See the following post for detail.

Specify the original name and the new name in dict like {original name: new name} to index / columns of rename().

index is for index name and columns is for the columns name. If you want to change either, you need only specify one of index or columns.

A new DataFrame is returned, the original DataFrame is not changed.

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

Related questions

0 votes
asked Nov 9, 2021 in Python Pandas by Robin
0 votes
asked Nov 9, 2021 in Python Pandas by Robin
...