tiber septim
tiber septim

Reputation: 47

How to rename columns in Pandas automatically?

I have a Dataframe with 240 columns. But they are named by number from 0 to 239.

How can I rename it to respectively 'column_1', 'column_2', ........, 'column_239', 'column_240' automatically? enter image description here

Upvotes: 2

Views: 653

Answers (2)

Tortar
Tortar

Reputation: 655

To do it with one column you can use

df.rename(columns = {0:'column_1'}, inplace = True)

Instead, for multiple columns

df.rename(columns = {x: "column_"+str(x+1) for x in range(0,240)}, inplace = True)

Upvotes: 3

mozway
mozway

Reputation: 261850

You can use:

df.columns = df.columns.map(lambda x: f'column_{x+1}')

Example output:

   column_1  column_2  column_3  column_4  column_5  column_6  column_7  column_8  column_9  column_10
0         0         1         2         3         4         5         6         7         8          9

Used input:

df = pd.DataFrame([range(10)])

Upvotes: 5

Related Questions