+1 vote
in Programming Languages by (66.8k points)
A dataframe has a header with some values (columns). I want to update the old column names with new values. How can I replace the old column names with new column names?

E.g.

current column names: ['c1', 'c2', 'c3']

new column names: ['col1', 'col2', 'col3']

1 Answer

+1 vote
by (281k points)
selected by
 
Best answer

You can use the columns attribute of the dataframe to replace old column names with new column names.

Here is an example to show how to use the columns attribute to add or update column names (header) of a pandas dataframe.

>>> import pandas as pd

>>> df = pd.DataFrame([[1,2,3],[4,5,6], [7,8,9]], columns=['c1', 'c2', 'c3'])

>>> df

   c1  c2  c3

0   1   2   3

1   4   5   6

2   7   8   9

>>> new_cols = ['col1', 'col2', 'col3']

>>> df.columns = new_cols

>>> df

   col1  col2  col3

0     1     2     3

1     4     5     6

2     7     8     9


...