Python Pandas Divide Two Columns

We will discuss how Python pandas divide two columns. pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. We will give two columns column1 and column2. Converting it to dataframe using pd.DataFrame() method. The Python program will divide those columns.

How to divide two columns: Division = column1 / column2

Mathematically,

Column1 = [4, 6, 8, 10]
Column2 = [2, 2, 4, 10]

Output:-

      Column1    Column2    Division
0        4          2          2
1        6          2          3
2        8          4          2
3        10         10         1

How to Divide Two Columns in Pandas

This is the simplest and easiest way to divide two columns in pandas. We will import pandas and take two columns while declaring the variables. Then, divide columns using division operators(/) and their division value will be stored in the division variable. Finally, it will be displayed on the screen.

Program description:- How to divide two columns element-wise in a pandas dataframe

# Python pandas divide two columns

# import pandas
import pandas as pd

# take inputs
df = pd.DataFrame({'column1':[4,9,10,15], 'column2':[2,3,5,15]})
# divide columns
df['division'] = df['column1'] / df['column2']

# print division value
print(df)

Output:-

      column1    column2     division
0       4          2           2.0
1       9          3           3.0
2       10         5           2.0
3       15         15          1.0

Pandas Divide Two Columns

In the previous program, divide columns using division operators but in this program, divide columns using pandas dataframe.div( ). The div() function returns floating division of dataframe and other, element-wise (binary operator truediv).

# Python pandas divide two columns

# import pandas
import pandas as pd

# take inputs
df = pd.DataFrame({'column1':[4,5,9,12], 'column2':[2,5,3,4]})
# divide columns
df['division'] = df['column1'].div(df['column2'].values)

# print division value
print(df)

Output:-

      column1  column2  division
0        4       2        2.0
1        5       5        1.0
2        9       3        3.0
3        12      4        3.0

Also See:- Python check if list contains same elements

Leave a Comment

Your email address will not be published.