简体   繁体   中英

Iteratively naming columns in a pandas DataFrame?

I feel like this should be easy but I couldn't find a solution.

The current column names are just: 0,1,2,3,4,5.

And I want to rename them to: bid_1, bidsize_1, bid_2, bidsize_2, bid_3, bidsize_3.

I've tried ['bid_' + str(i) for i in range(1,4)] + ['bidsize_' + str(i) for i in range(1,4)] and got ['bid_1', 'bid_2', 'bid_3', 'bidsize_1', 'bidsize_2', 'bidsize_3'] . But the ordering is not what I wanted.

try this-

df.columns = [s+str(i+1) for i in range(len(df.columns)//2) for s in ['bid_', 'bidsize_']]
['bid_1',
 'bidsize_1',
 'bid_2',
 'bidsize_2',
 'bid_3',
 'bidsize_3']

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