11

I would like to rename the column names, but the Data Frame contains similar column names. How do I rename them?

df.columns

Output:

Index([ 'Goods',
       'Durable goods','Services','Exports', 'Goods', 'Services', 'Imports', 'Goods', 'Services']

Here, there are three goods columns that have similar names. How can I rename a specific column?

Ethan
  • 1,625
  • 8
  • 23
  • 39
Antony Naveen
  • 121
  • 1
  • 1
  • 5

2 Answers2

11

You can use this:

df.columns = ['Goods_1', 'Durable goods','Services','Exports', 'Goods_2', 'Services', 'Imports', 'Goods_3', 'Services']

or if you have too many columns:

cols = []
count = 1
for column in df.columns:
    if column == 'Goods':
        cols.append(f'Goods_{count}')
        count+=1
        continue
    cols.append(column)
df.columns = cols
Yury Wallet
  • 103
  • 2
Mohit Motwani
  • 601
  • 1
  • 7
  • 23
2

You can rename column name based on its position too:

df.rename(columns={ df.columns[1]: "new_col_name" })

Note: If you have similar columns names, all of them will be renamed.

Stephen Rauch
  • 1,783
  • 11
  • 21
  • 34
mannu
  • 108
  • 5