Learn about How to Divide Two Columns in Pandas in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Pandas is a terrific Python module that allows you to manipulate data frames and datasets. It has a number of features that allow for efficient manipulation. In pandas, there are times when you need to separate two columns.
How to Divide Two Columns in Pandas
The simple division (/) operator can be used to divide two columns. Column 1 will be divided with the help of other columns in this section. As you can see in the code below, we first create data and then convert it to a dataframe using the pd.DataFrame()
method. Finally, we divide df[“col1”] by df[“col2”] and add the result to the result column.
Source code:
# Python pandas divide two columns
# import pandas
import pandas as pd
# dataframe
df = pd.DataFrame({'column1':[4,9,10,15], 'column2':[2,3,5,15]})
# divide columns
df['division'] = df['column1'] / df['column2']
#print dataframe
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
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Python Program to Print ASCII Table