简体   繁体   中英

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 ...

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)]

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM