2017-07-07 110 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