How to multiply and divide on a Pandas DataFrame using Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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]})
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.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚