在pandas中迭代生成列名

2024-05-15 17:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个11列的Pandas数据框,df

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

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

^{pr2}$

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

你能告诉我如何迭代地将名称改为type_*或{}?在哪里

* = half the number of columns excluding the first one (Name)

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


Tags: the数据name名称pandasdffffiii
1条回答
网友
1楼 · 发布于 2024-05-15 17:11:02

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

# 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]

相关问题 更多 >