1

I have a pandas dataframe with 120 columns. The columns look something like this:

0_x     1_x     2_x     3_x     4_x     5_x     6_x     7_x     8_x     0_y     ...     65 ... 120

How can I rename them in a single movement?. I read the documentation and found that the way of renaming columns in pandas was:

df.columns = ['col1', 'col2', 'col3']

The issue is that I writing a list of more than 120 columns could be very odd. Which alternatives exist for this problem?. Let's say I would like to name all the columns something like: col1 to colN.

student
  • 347
  • 3
  • 13

1 Answers1

5

Easy enough with a list comprehension and enumerate or range:

df.columns = ['col%s' % i for i in range(len(df.columns))]
df.columns = ['col%s' % i for i, c in enumerate(df.columns)]

I prefer enumerate, even though you are just throwing away the column names. No firm reason, I just dont like the look of func(func(something)) and avoid it when I can.

Karnage
  • 677
  • 4
  • 9
  • 2
    You don't have to specify `c` in your enumerate and can instead use `df.columns = ['cols%s' % i for i, __ in enumerate(df.columns)]` to signal to readers that you are throwing away the variable. Entirely personal preference though: http://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python – TheF1rstPancake Nov 16 '16 at 03:48