Home > OS >  Trim string in column with substring in other column
Trim string in column with substring in other column

Time:09-10

df = pd.DataFrame({
  "string": ["abc", "def", "ghi"],
  "substring": ["bc", "e", "ghi"]
})

Is an operation like this possible?

df['string']=df['string'].replace(df['substring'], r'')

expected result:

string substring 
a      bc        
df     e        
       ghi       

CodePudding user response:

Use lsit comprehension:

df['string']= [a.replace(b, '') for a, b in zip(df['string'], df['substring'])]
print (df)
  string substring
0      a        bc
1     df         e
2              ghi
  • Related