×

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

How to divide two columns element-wise in a pandas dataframe?

Given a pandas dataframe, we have to divide two columns element-wise.
Submitted by Pranit Sharma, on November 14, 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.

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both row & column values.

Problem statement

We are given a DataFrame with two columns A and B, we need to divide column A with column B, values by value.

Dividing two columns element-wise

For this purpose, we will simply define an expression of df['A']/df['B'] and store the result in a new column.

This expression runs in a way so that it takes the first value of column A at a time and divides it by the first value of column B and so on and stores the corresponding value of the new column.

Let us understand with the help of an example,

Python program to divide two columns element-wise in a pandas dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a Dictionary
d = {
    'A':[12,18,90,24,50],
    'B':[6,9,10,3,25]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Creating new column
df['New'] = df['A']/df['B']

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

Output

The output of the above program is:

Example: Divide two columns element-wise

Python Pandas Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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