我有一个 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 列的大表。
请您参考如下方法:
编辑:这将更适合任意数量的列(偶数或奇数)
# 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]
