Ronnie
Ronnie

Reputation: 391

add numeric prefix to pandas dataframe column names

how would I add variable numeric prefix to dataframe column names

If I have a DataFrame df

  colA  colB
0  A      X
1  B      Y
2  C      Z

How would I rename the columns according to the number of columns. Something like this:

  1_colA  2_colB 
0  A      X              
1  B      Y
2  C      Z

The actually number of columns is very large to be renamed manually

Thanks for the help

Upvotes: 3

Views: 1432

Answers (1)

jezrael
jezrael

Reputation: 863301

Use enumerate for count with f-strings and list comprehension:

#python 3.6+
df.columns = [f'{i}_{x}' for i, x in enumerate(df.columns, 1)]
#python below 3.6
#df.columns = ['{}_{}'.format(i, x) for i, x in enumerate(df.columns, 1)]
print (df)
  1_colA 2_colB
0      A      X
1      B      Y
2      C      Z

Upvotes: 4

Related Questions