Pandas subtract two dataframes based on column

In Pandas, you can subtract two dataframes based on a specific column by using the df.subtract() method. This method performs element-wise subtraction between two dataframes, aligning them based on their index and column names.

Let’s consider an example to understand this better.

import pandas as pd

# Create the first dataframe
df1 = pd.DataFrame({
  'A': [10, 20, 30],
  'B': [40, 50, 60]
})

# Create the second dataframe
df2 = pd.DataFrame({
  'A': [5, 10, 15],
  'B': [20, 30, 40]
})

# Subtract the second dataframe from the first dataframe based on column 'A'
result = df1['A'].subtract(df2['A'])

print(result)
    

The output of this code will be:

0    5
1    10
2    15
dtype: int64
  

Here, we created two dataframes df1 and df2 with the same column names ‘A’ and ‘B’. We then subtracted the values of column ‘A’ from df2 from the values of column ‘A’ from df1 using the df.subtract() method.

The resulting dataframe result contains the element-wise subtraction of the values, where each value is subtracted from its corresponding value in the other dataframe based on the index.

You can perform this subtraction on any column of the dataframes by replacing 'A' with the desired column name in the df.subtract() method.

Leave a comment