简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM