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.

1 Answer 1

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.

1
  • 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: stackoverflow.com/questions/5893163/… Nov 16, 2016 at 3:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.