Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame: Subtract columns with string datatype

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' '---'
like image 275
Lorenz Avatar asked Jun 07 '26 05:06

Lorenz


1 Answers

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  --
like image 199
anky Avatar answered Jun 10 '26 19:06

anky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!