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

269
Visualizações
Replacing Substring with another string from column Pandas

Got this DataFrame:

Type String ext_id int_id
1 UKidBC 2393 2820
1 UKidBC 4816 1068
0 UKidBC 4166 3625
0 UKidBC 2803 1006
1 UKidBC 1189 2697

For each value on String column, I need to replace the substring 'id' (UKidBC) according to the following rule:

If df['Type'] = 1 then replace substring 'id' with the corresponding df['int_id'] value else replace substring 'id' with the corresponding df['ext_id'] value.

I tried to use that line:

new_df.apply(lambda x: x['string'].replace(pat=['id'], 
   repl=x['int_id']) if x['Type'] == 1
   else x['string'].replace(pat=['id'],repl=x['ext_id']),axis=1)

Keep getting this error:

str.replace() takes no keyword arguments

What I am doing wrong here?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Instead of apply, we could use str.split + np.where to replace values according to "Type" value:

tmp = df['String'].str.split('id', expand=True)
df['String'] = tmp[0] + np.where(df['Type'].astype(bool), df['int_id'].astype(str), df['ext_id'].astype(str)) + tmp[1]

Output:

   Type    String  ext_id  int_id
0     1  UK2820BC    2393    2820
1     1  UK1068BC    4816    1068
2     0  UK4166BC    4166    3625
3     0  UK2803BC    2803    1006
4     1  UK2697BC    1189    2697
over 4 years ago · Santiago Trujillo Relatório

0

Assuming your string is fixed, use numpy.where and vector string concatenation:

df['String'] = df['String'].str[:2] + np.where(df['Type'].eq(1), df['int_id'], df['ext_id']) + df['String'].str[4:]
over 4 years ago · Santiago Trujillo Relatório

0

Use the same idea as yours (apply(), replace()), just modify a bit about using replace().

new_df["String"] = new_df.apply(
    lambda row: row["String"].replace("id", row["int_id"]) if row["type"] == 1 else row["String"].replace("id", row["ext_id"]),
    axis=1
)

output:

   Type    String  ext_id  int_id
0     1  UK2820BC    2393    2820
1     1  UK1068BC    4816    1068
2     0  UK4166BC    4166    3625
3     0  UK2803BC    2803    1006
4     1  UK2697BC    1189    2697
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