Divide two Columns in Pandas

How to divide two Columns in Pandas : Various Methods

Popular Domains for just 99 Cents at Namecheap!

Pandas is a great python module that allows you to manipulate the dataframe or your dataset. There are many functions in it that efficiently do manipulation. There is a time where you need to divide two columns in pandas. In this entire tutorial, you will how to divide two columns in pandas using different methods.

Methods to divide two columns in Pandas

In this section, you will know all the methods to divide two columns in pandas. Please note that I am implementing all the examples on Jupyter Notebook. Make sure to do it for better understanding.

Method 1: Using a simple division operator

The first method you can use to divide two columns is the simple division (/) operator. Here you will divide column1 with other columns.

Execute the below lines of code.

import pandas as pd
data = {"col1":[100,200,300,400,500],"col2":[10,20,30,40,50]}
df= pd.DataFrame(data)
df["result"] = df["col1"]/df["col2"]
print(df)

You can see in the above code I am first creating data and converting it to dataframe using pd.DataFrame() method. Lastly, I am dividing df[“col1”] with df[“col2”] and assigning it to the result column.

When you will run the code you will get the following output.

Output

Dividing two column using division operator
Dividing two column using division operator

Method 2: Pandas divide two columns using div() function

The second method to divide two columns is using the div() method. It divides the columns elementwise. It accepts scalar value, series, or dataframe as an argument for dividing with the axis. If the axis is 0 the division is done row-wise and if the axis is 1 then division is done column-wise.

Execute the below lines of code.

import pandas as pd
data = {"col1":[100,200,300,400,500],"col2":[10,20,30,40,50]}
df= pd.DataFrame(data)
df["result"] = df["col1"].div(df["col2"].values)
print(df)

In the above, you can see I am dividing col1 with the value of col2 bypassing the df[“col2”] .values as an argument. By default, the axis is 0.

Output

Dividing two column using division operator
Dividing two column using div() function

 

Conclusion

Pandas python module can do fast manipulation on any dataframe. These are the method to divide two columns in dataframe. You can use any of them. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Source:

Pandas div Documentation

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner