Reputation: 3677
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
I can use df.rename
but I will have to manually type in the new names.
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)
I ask this because I want to generalize this naming system to a large table with 1000 columns.
Upvotes: 3
Views: 7741
Reputation: 5225
Edit: 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]
Upvotes: 9