在 pandas 中迭代生成列名 [英] generating column names iteratively in pandas
本文介绍了在 pandas 中迭代生成列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个11列的Pandas DataFrame,df
I have an 11 column Pandas DataFrame, df
Name aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk
我想重命名列,以便新标题为
I want to rename the columns so that the new header is
Name type_1 type_2 type_3 type_4 type_5 expt_1 expt_2 expt_3 expt_4 expt_5
我可以使用df.rename
,但必须手动输入新名称.
I can use df.rename
but I will have to manually type in the new names.
您能告诉我如何将名称迭代地更改为type_*
或expt_*
吗?
Can you tell me how I can change the names iteratively to type_*
or expt_*
? where
* = half the number of columns excluding the first one (Name)
之所以问这个问题,是因为我想将这个命名系统推广到一个具有1000列的大表中.
I ask this because I want to generalize this naming system to a large table with 1000 columns.
推荐答案
编辑:这将更适合于任意数量的列(偶数或奇数)
this will be better suited to an arbitrary number of columns (either even or odd in number)
# 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]
这篇关于在 pandas 中迭代生成列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文