Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

272
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda