How to perform addition and subtraction in Pandas using Python

1 min

Here is how to perform additions and subtraction  in Pandas using Python

Sample dataframe

# Import the Pandas library
import pandas as pd

# We create our example dataframe
df = pd.DataFrame(index = [2018, 2019, 2020, 2021, 2022], data=
                  {"eu_sales" : [12334, 12344, 521323, 709123, 1024566],
                   "us_sales" : [10452, 24198, 345222, 629452, 925123]})
We create our example dataframe


On columns

You can either sum up individual columns or use the .sum() method.

# Summing up individual columns
print(df["eu_sales"] + df["us_sales"])
Summing up individual columns
# Summing up all columns
Summing up all columns using the sum() method
df["total_sales"] = df["eu_sales"] + df["us_sales"]
Creating a new column with the result of our addition

On rows

# Summing up all rows
Summing up all rows using the sum() method


# Subtracting individual columns
print(df["total_sales"] - df["us_sales"])
Summing up individual columns

Here you are, you know pretty much everything that you would need about addition and subtraction with Pandas using Python.