Binary Operations
Binary operations in a DataFrame involve operations performed between two DataFrames or a DataFrame and
a scaler value. These operations include addition, subtraction, multiplication and division.
Basic Binary Operations:
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
1. Addition Binary operation [using +, add() and radd()]
We can perform add binary operation on two DataFrame objects using either:
• + operator
• Using add()
• By using radd() {reverse add}
• import pandas as pd
• data = [
• [20,22,24,28],
• [18,16,17,32],
• [34,37,32,31],
• [10,12,41] # NaN value in last column
• ]
• data2 = [
• [5,6,7,8],
• [2,6,9,7],
• [1,7,3,6],
• [7,5,3,4]
• ]
• d1 = [Link](data)
• d2 = [Link](data2)
•
• print(d1+d2)
• print([Link](d2))
• print([Link](d2))
Important points:
• Whenever any column of a DataFrame has a NaN value in it, then its type is automatically changed to
floating point because in Python integer types cannot store NaN values.
• When + is performed on string values it concatenates them.
• import pandas as pd
• data = [
• ["Tony","Bruce","Peter"],
• ["Thor","Steven","Steve"]
• ]
•
• data2 = [
• ["Stark","Banner","Parker"],
• ["Odinson","Strange","Rogers"]
• ]
• d1 = [Link](data)
• d2 = [Link](data2)
•
• print([Link](d2))
•
2. Subtraction Binary operation:
We can perform subtraction binary operation on two DataFrame objects using either
• Minus - operator
• Using sub()
• Using rsub()
• import pandas as pd
• data = [
• [20,22,24,28],
• [18,16,17,32],
• [34,37,32,31],
• [10,12,41] # NaN value in last column
• ]
• data2 = [
• [5,6,7,8],
• [2,6,9,7],
• [1,7,3,6],
• [7,5,3,4]
• ]
• d1 = [Link](data)
• d2 = [Link](data2)
•
• print(d1-d2)
• print([Link](d2))
• print([Link](d2))
3. Multiplication Binary operation:
We can perform Multiplication binary operation on two DataFrame objects using either
• * operator
• Using mul()
• Using rmul()
• import pandas as pd
• data = [
• [20,22,24,28],
• [18,16,17,32],
• [34,37,32,31],
• [10,12,41] # NaN value in last column
• ]
• data2 = [
• [5,6,7,8],
• [2,6,9,7],
• [1,7,3,6],
• [7,5,3,4]
• ]
• d1 = [Link](data)
• d2 = [Link](data2)
•
• print(d1*d2)
• print([Link](d2))
• print([Link](d2))
4. Division Binary operation:
We can perform Division binary operation on two DataFrame objects using either
• / operator
• Using div()
• Using rdiv()
• import pandas as pd
• data = [
• [20,22,24,28],
• [18,16,17,32],
• [34,37,32,31],
• [10,12,41] # NaN value in last column
• ]
• data2 = [
• [5,6,7,8],
• [2,6,9,7],
• [1,7,3,6],
• [7,5,3,4]
• ]
• d1 = [Link](data)
• d2 = [Link](data2)
•
• print(d1/d2)
• print([Link](d2))
• print([Link](d2))