How to multiply and divide on a Pandas DataFrame using Python

1 min

Here is how to multiply and divide on a Pandas DataFrame using Python.

Sample data frame

# Import the Pandas library
import pandas as pd

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

Multiply

On columns

# Multiplying the column values by a float
print(df["eur_sales"] * 1.02)
Multiply the column by a float
# Multiplying the column values by another column (element wise)
print(df["eur_sales"] * df["eur_sales"])
Multiply the column by another column

On rows

On rows, one can do a cumulative product using the .cumprod() method.

Which multiplies every column by the last one, following the index.

# Performing a row wise cumulative product
print(df["eur_sales"].cumprod())
Multiply the column by a float

Divide

On columns

# Multiplying the column values by a float
print(df["eur_sales"] / 12)
Divide the column by a float
# Multiplying the column values by another column (element wise)
print(df["eur_sales"] / df["usd_sales"])
Divide the column by another column

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