Home > Blockchain >  How to add a suffix to the first N columns in pandas?
How to add a suffix to the first N columns in pandas?

Time:08-26

I want to add a suffix to the first N columns. But I can't.

This is how to add a suffix to all columns:

import pandas as pd

df = pd.DataFrame( {"name" : ["John","Alex","Kate","Martin"], "surname" : ["Smith","Morgan","King","Cole"],
                    "job": ["Engineer","Dentist","Coach","Teacher"],"Age":[25,20,25,30],
                    "Id": [1,2,3,4]})

df.add_suffix("_x")

And this is the result:

    name_x    surname_x   job_x      Age_x   Id_x
0   John      Smith       Engineer   25      1
1   Alex      Morgan      Dentist    20      2
2   Kate      King        Coach      25      3
3   Martin    Cole        Teacher    30      4

But I want to add the first N columns so let's say the first 3. Desired output is:

    name_x    surname_x   job_x      Age     Id
0   John      Smith       Engineer   25      1
1   Alex      Morgan      Dentist    20      2
2   Kate      King        Coach      25      3
3   Martin    Cole        Teacher    30      4

CodePudding user response:

Work with the indices and take slices to modify a subset of them:

df.columns = (df.columns[:3] '_x').union(df.columns[3:], sort=False)

print(df)
   name_x surname_x     job_x  Age  Id
0    John     Smith  Engineer   25   1
1    Alex    Morgan   Dentist   20   2
2    Kate      King     Coach   25   3
3  Martin      Cole   Teacher   30   4

CodePudding user response:

This should work:

N=3
cols=[i for i in df.columns[:N]]
new_cols=[i '_x' for i in df.columns[:N]]
dict_cols=dict(zip(cols,new_cols))
df.rename(dict_cols,axis=1)

CodePudding user response:

set the column labels using a list comprehension:

n = 3
df.columns = [f'{c}_x' if i < n else c for i, c in enumerate(df.columns)]

results in

   name_x surname_x     job_x  Age  Id
0    John     Smith  Engineer   25   1
1    Alex    Morgan   Dentist   20   2
2    Kate      King     Coach   25   3
3  Martin      Cole   Teacher   30   4
  • Related