student student - 24 days ago 8
Python Question

How to rename a long pandas dataframe with toy names?

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
.

Answer

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.