我有一个11列的Pandas DataFrame,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.rename
,但我必须手动输入新名称。
您能告诉我如何将名称迭代更改为type_*
或expt_*
吗?
* = half the number of columns excluding the first one (Name)
我问这个是因为我想把这个命名系统推广到一个1000列的大表。
答案 0 :(得分:4)
编辑:这将更适合任意数量的列(数量为偶数或奇数)
# 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]