简体   繁体   English

迭代命名 pandas DataFrame 中的列?

[英]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.当前的列名只是: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.我想将它们重命名为: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'] .我试过['bid_' + str(i) for i in range(1,4)] + ['bidsize_' + str(i) for i in range(1,4)]并得到['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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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