Home »
Python »
Python Programs
Python - Logical operation on two columns of a dataframe
Given a pandas dataframe, we have to perform Logical operation on two columns of the dataframe.
By Pranit Sharma Last updated : September 29, 2023
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.
Problem statement
Suppose, we have a DataFrame and we want to create a column that contains the values accessed from the Boolean operation of two columns.
Performing logical operation on two columns of a dataframe
For this purpose, Python has very easy keywords for logical operations. AND, OR, NOR, NOT, XOR, and XNOR are an example of some basic logical operations.
We will find out AND operation of two columns and store it in another column, we will achieve this task by either using & or by writing the keyword and.
Let us understand with the help of an example,
Python program to perform logical operation on two columns of a dataframe
# Importing pandas package
import pandas as pd
# Creating two dictionaries
d1 = {
'Can_afford':[True,True,False,True,False],
'Bought':[False,False,False,True,False]
}
# Creating DataFrame
df = pd.DataFrame(d1)
# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")
df['reverse'] = df['Can_afford'] & df['Bought']
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »