1

I have two dataframes:

df_1 = pd.DataFrame({'a' : [7,8, 2], 'b': [6, 6, 11], 'c': [4, 8, 6]})
df_1

df_1

and

df_2 = pd.DataFrame({'d' : [8, 4, 12], 'e': [16, 2, 1], 'f': [9, 3, 4]})
df_2

df_2

My goal is something like:

expected output

In a way that 'in one shot' I can subtract each column multiple times.

I'm trying for loop but I´m stuck!

tdy
  • 36,675
  • 19
  • 86
  • 83
Victor Castro
  • 105
  • 1
  • 6

1 Answers1

4

You can subtract them as numpy arrays (using .values) and then put the result in a dataframe:

df_3 = pd.DataFrame(df_1.values - df_2.values, columns=list('xyz'))

#     x   y  z
# 0  -1 -10 -5
# 1   4   4  5
# 2 -10  10  2

Or rename df_1.columns and df_2.columns to ['x','y','z'] and you can subtract them directly:

df_1.columns = df_2.columns = list('xyz')
df_3 = df_1 - df_2

#     x   y  z
# 0  -1 -10 -5
# 1   4   4  5
# 2 -10  10  2
tdy
  • 36,675
  • 19
  • 86
  • 83