Home > Blockchain >  Subtract one text column from the other using pandas
Subtract one text column from the other using pandas

Time:01-26

I want to remove the text that within one column from the other column vectorially. Meaning, without using loop or apply. I found this solution that no longer works old solution link.

Input:

pd.DataFrame({'A': ['ABC', 'ABC'], 'B': ['A', 'B']})

     A  B
0   ABC A
1   ABC B

Desired output:

0    BC
1    AC

CodePudding user response:

Use a list comprehension:

df['C'] = [a.replace(b, '') for a,b in zip(df['A'], df['B'])]

Output:

     A  B   C
0  ABC  A  BC
1  ABC  B  AC

If you want a Series:

out = pd.Series([a.replace(b, '') for a,b in zip(df['A'], df['B'])], index=df.index)

Output:

0    BC
1    AC
dtype: object
  • Related