Andrew
Andrew

Reputation: 137

How to change the column names of a Pandas DataFrame?

I have a Pandas DataFrame with n columns , don't know how many columns will be there.

    df = index  task_1   task_2 ......
          0     dummy_1   dummy_2 ....
          1     dum_1     dum_2 ...

I want to change the names of the column from task_1 to Label_1 and so on.The out put needs to be

    df = index  Label_1   Label_2 ......
          0     dummy_1   dummy_2 ....
          1     dum_1     dum_2 ...

Upvotes: 2

Views: 257

Answers (3)

aminrd
aminrd

Reputation: 5070

You can iterate through all columns and replace "task" with "Label" like this. And this only applies to columns that has "task" in their name and others remains unchanged:

df.columns = [name.replace('task', 'Label') for name in df.columns]

Upvotes: 1

Prabhat Kumar Sahu
Prabhat Kumar Sahu

Reputation: 994

You still need to find out how many columns are there

You can do that by

len(df.columns)

and you can change the names in sequence by iterating through a loop for eg"

df.columns=["Label_"+str(i) for i in range(1, 17)]

Upvotes: 2

Andrew Eckart
Andrew Eckart

Reputation: 1726

Use the DataFrame.rename method, passing a dictionary to the columns argument where the keys are the old column names and the values are the new column names:

df.rename(columns={"task_1": "Label_1"}, inplace=True)

Upvotes: 0

Related Questions