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

268
Views
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 answers
Answer question

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 Report

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 Report

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 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!