Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

809
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda