How to multiply and divide on a Pandas DataFrame using Python
• 1 minHere 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]})
Multiply
On columns
# Multiplying the column values by a float
print(df["eur_sales"] * 1.02)
# Multiplying the column values by another column (element wise)
print(df["eur_sales"] * df["eur_sales"])
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())
Divide
On columns
# Multiplying the column values by a float
print(df["eur_sales"] / 12)
# Multiplying the column values by another column (element wise)
print(df["eur_sales"] / df["usd_sales"])
Here you are, you know pretty much everything that you would need about multiplication and division with Pandas using Python.