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.

Dividing two columns element-wise

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

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.

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.

Let us understand with the help of an example,

Python code 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:

Example: Divide two columns element-wise

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.