How can I subtract two columns that contain values of type string? No values are indicated by '---' and should lead to a '---' in the result. The result should also be of value type string.
Source
df1 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['5', '---', '7']})
x y
0 'a' '5'
1 'b' '---'
2 'c' '7'
df2 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['1', '2', '---']})
x y
0 'a' '1'
1 'b' '2'
2 'c' '---'
Target
df3 = df1 - df2
x y
0 'a' '4'
1 'b' '---'
2 'c' '---'
Try with:
df1.set_index('x').apply(lambda x: pd.to_numeric(x,errors='coerce')).sub(
df2.set_index('x').apply(lambda x: pd.to_numeric(x,errors='coerce'))).fillna('--')\
.reset_index()
x y
0 a 4
1 b --
2 c --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With