2017-07-07 114 views
0

我有一个11列大熊猫据帧,DF生成列名重复的大熊猫

Name aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk 

我想,这样的新标头是

Name type_1 type_2 type_3 type_4 type_5 expt_1 expt_2 expt_3 expt_4 expt_5 

我可以用DF的重命名列。重命名,但我将不得不手动输入新名称。你能告诉我如何改变名字迭代到type_ *或expt_ *,其中* =不包括第一个(名称)的列数的一半。我问这个是因为我想把这个命名系统推广到一个有1000列的大型表格。

回答

2

编辑:这将是更适合于列(奇数或偶数数量)

# get length of df's columns 
num_cols = len(list(df)) 

# generate range of ints for suffixes 
# with length exactly half that of num_cols; 
# if num_cols is even, truncate concatenated list later 
# to get to original list length 
rng = range(1, (num_cols/2) + 1) 

new_cols = ['Name'] + ['type_' + str(i) for i in rng] + ['expt_' + str(i) for i in rng] 

# ensure the length of the new columns list is equal to the length of df's columns 
df.columns = new_cols[:num_cols] 
+1

RNG =范围(1的任意数量的,INT((LEN(列表(DF)) - 1)/ 2)+1))#建议添加到获得长度 –

+0

@AntonvBR是的,这绝对是更一般化,但内部计算的结果将已经是int类型。现在编辑答案。 – cmaher