Get absolute value difference between one df column one by one and all values in another df column, creating a new column for each result in pandas

Viewed 138

This may be simple but I'm relatively new and can't figure out quite the right search terms.

I have two dataframes, examples below. I want to take all the values in col_add from df2, and get the abs value difference to all the values in df1 col_1, adding a new column for each set of results.

df1 = pd.DataFrame({'col_1':[1,2,3], 'col_2':['d','e','f']})
df1
col_1   col_2
0   1   d
1   2   e
2   3   f

df2 = pd.DataFrame({'col_add':[4,2,1],})
df2
    col_add
0   4
1   2
2   1

The desired result would look like:

col_1   col_2   res_0   res_1   res_2
0   1    d       3        1       0
1   2    e       2        0       1
2   3    f       1        1       2

Not sure if there is an efficient way to do this? The data real data sets I'd like to use this for have between 100 and 500 rows. Any help would be much appreciated!

1 Answers

Convert columns to numpy by Series.to_numpy with broadcasting to 2d array, so possible pass to new DataFrame and add to original:

arr = np.abs(df1['col_1'].to_numpy()[:, None] - df2['col_add'].to_numpy())

df = df1.join(pd.DataFrame(arr).add_prefix('res_'))
print (df)
   col_1 col_2  res_0  res_1  res_2
0      1     d      3      1      0
1      2     e      2      0      1
2      3     f      1      1      2
Related