在熊猫中迭代生成列名

Ssa*_*ank 1 python pandas

我有一个11列的Pandas DataFrame, df

Name aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk
Run Code Online (Sandbox Code Playgroud)

我想重命名列,以便新的标题是

Name type_1 type_2 type_3 type_4 type_5 expt_1 expt_2 expt_3 expt_4 expt_5
Run Code Online (Sandbox Code Playgroud)

我可以使用,df.rename但必须手动输入新名称。

您能告诉我如何将名称迭代更改为type_*expt_*吗?哪里

* = half the number of columns excluding the first one (Name)
Run Code Online (Sandbox Code Playgroud)

我问这个问题是因为我想将这个命名系统推广到一个有1000列的大表中。

cma*_*her 5

编辑:这将更适合于任意数量的列(无论是偶数还是奇数)

# 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]
Run Code Online (Sandbox Code Playgroud)