×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Multiply two columns in a pandas dataframe and add the result into a new column

Given a DataFrame, we need to multiply two columns in this DataFrame and add the result into a new column. By Pranit Sharma Last updated : September 25, 2023

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.

Problem statement

Given a DataFrame, we need to multiply two columns in this DataFrame and add the result into a new column.

Multiplying two columns in a pandas dataframe and add the result into a new column

For this purpose, we will first create a DataFrame, the dataframe will contain 2 columns initially and we will perform a row-wise product of both columns and store all the values in a list. Finally, we will assign this list to a new column of the DataFrame.

Let us understand with the help of an example,

Python program to multiply two columns in a pandas dataframe and add the result into a new column

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'A':[10,20,30,40,50],
    'B': [10,20,30,40,50]
}

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

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

# Creating a list of values
list = []
for i in range(len(df['A'])):
    a = (df['A'][i]*df['B'][i])
    list.append(a)

# Creating a new column and assigning 
# its values as the list defined above
df['Product'] = list

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

Output

The output of the above program is:

Example: Multiply two columns

Python Pandas Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.