Python - How to multiply columns by a column in Pandas?

Given a DataFrame, we need to multiply columns by a column in this DataFrame.
Submitted by Pranit Sharma, on August 04, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

To multiply columns by a column, we will first create a DataFrame, the dataframe will contain 2 columns initially and we use pandas.DataFrame.multiply() method and store all the values in another variable. Finally, we will assign this list to a new column of the DataFrame.

pandas.DataFrame.multiply() Method

This method is used to multiply two dataframe columns, we need to define the column which has to be multiplied inside square brackets with our dataframe like df[col], and then multiply() method will take another column with whom we want to multiply.

Note, if we have multiple columns to multiply, we will pass a list of column names inside square brackets with our dataframe like df[[col1, col2]].

Let us understand with the help of an example,

Python code to multiply columns by a column in Pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Food':['Burger','Pizza','Noodles','Pasta'],
    'Actual_Price':[70,250,120,150],
    'After_discount':[66,240,113,140],
    'Sales':[13,24,43,65]
}

# Creating a dataframe
df = pd.DataFrame(d)

# Display Dataframe
print("DataFrame :\n",df,"\n")

# Multiply columns
result = df[["Actual_Price", "After_discount"]].multiply(df["Sales"], axis="index")

# Display result
print("Result:\n",result)

Output:

Example: multiply columns by a column

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.