Ilan Geffen
Ilan Geffen

Reputation: 181

Subtract one text column from the other using pandas

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

Upvotes: 1

Views: 51

Answers (1)

mozway
mozway

Reputation: 260390

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

Upvotes: 2

Related Questions