3

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.

Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
Ssank
  • 3,367
  • 7
  • 28
  • 34

1 Answers1

9

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]
cmaher
  • 5,100
  • 1
  • 22
  • 34
  • 1
    rng = range(1, int((len(list(df))-1)/2)+1)) # suggestion added to get the length – Anton vBR Jul 07 '17 at 20:26
  • @AntonvBR yes, that's definitely more generalized, though the result of the inner calculation will already be of type int. Editing the answer now. – cmaher Jul 07 '17 at 20:39