Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

808
Views
How to add prefix to column names except some columns?

This is an adaptation of a question posed by @ScalaBoy here and answered by @timgeb, the question is the same, except it is about a prefix not suffix:

Given pandas DataFrame, how can I add the prefix "new_" to all columns except two columns Id and Name?

import pandas as pd
data = [[1,'Alex',22,'single'],[2,'Bob',32,'married'],[3,'Clarke',23,'single']]
df = pd.DataFrame(data,columns=['Id','Name','Age','Status'])
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Use add_prefix. This function is applied to the whole dataframe. To hide columns you dont need renamed, set them as index. After renaming you can reset back the index. Code below

df=df.set_index(['Id', 'Name']).add_prefix('new_').reset_index()



    Id    Name  new_Age new_Status
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single
over 4 years ago · Santiago Trujillo Report

0

You can use rename method:

df.rename({col:'new_'+ col for col in df.columns[~df.columns.isin(['Id','Name'])]}, axis=1)
over 4 years ago · Santiago Trujillo Report

0

df.rename(columns = lambda col: f"new_{col}" 
                                if col not in ('Name', 'Id') 
                                else col
          )

   Id    Name  new_Age new_Status
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single

You could achieve it with regex; however, in my opinion, it is not as clear as the previous solution:


new_col = df.columns.str.replace(pat = r"\b(?!Id|Name\b).+", 
                                 repl = lambda m: f"new_{m[0]}", 
                                 regex=True)

df.set_axis(new_col, axis=1) # or df.columns = new_col

   Id    Name  new_Age new_Status
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!