1

I have a Dataframe like this

df:
   X  Y  Z
0  1  0  0
1  0  1  0
2  0  0  1

If I want to rename the columns with a string and number in the range(0, 3) like this

df:
  new_0  new_1  new_2
0     1      0      0
1     0      1      0
2     0      0      1

What can I do?

Actually, in my case I have about 73 columns which should be renamed, so I think that I can not just rename each column one by one.

Thanks~

jpp
  • 159,742
  • 34
  • 281
  • 339
Sun Hao Lun
  • 313
  • 2
  • 10
  • 1
    Possible duplicate of [Renaming columns in pandas](https://stackoverflow.com/questions/11346283/renaming-columns-in-pandas) – Sheldore Dec 15 '18 at 14:33
  • Something like: `df.columns = [f'new_{n}' for n in enumerate(df.columns)]` ? – Jon Clements Dec 15 '18 at 14:33
  • Actually, in my case I have about 73 columns which should be renamed, so I think that I can not just rename each column one by one. – Sun Hao Lun Dec 15 '18 at 14:40

2 Answers2

3

Assume you have a function rename() to map your old column to new column, then it will be as easy as this:

df.columns = [rename(c) for c in df.columns]

I do not know if you mean this, but if you simply want to renumber your columns, this is what to do:

df.columns = ["new_%d" % i for i,_ in enumerate(df.columns)]
adrtam
  • 6,991
  • 2
  • 12
  • 27
2

You can use Pandas / NumPy functionality:

df.columns = np.arange(df.shape[1])
df = df.add_prefix('new_')

Or you can use a list comprehension with f-strings (Python 3.6; PEP498):

df.columns = [f'new_{i}' for i in range(df.shape[1])]
jpp
  • 159,742
  • 34
  • 281
  • 339