Python Pandas – Can we use & Operator to find common columns between two DataFrames?

PythonServer Side ProgrammingProgramming

Yes, we can use the & operator to find the common columns between two DataFrames. At first, let us create two DataFrames −

# creating dataframe1
dataFrame1 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
})

print("Dataframe1...\n",dataFrame1)

# creating dataframe2
dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

Get the common columns using the & operator −

res = dataFrame1.columns & dataFrame2.columns

Example

Following is the code −

import pandas as pd

# creating dataframe1
dataFrame1 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
})

print"Dataframe1...\n",dataFrame1

# creating dataframe2
dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

print"Dataframe2...\n",dataFrame2

# getting common columns using the & operator
res = dataFrame1.columns & dataFrame2.columns

print"\nCommon columns...\n",res

Output

This will produce the following output −

Dataframe1...
        Car   Cubic_Capacity
0       BMW             2000
1     Lexus             1800
2     Tesla             1500
3   Mustang             2500
4  Mercedes             2200
5    Jaguar             3000
Dataframe2...
        Car   Units_Sold
0       BMW          100
1     Lexus          110
2     Tesla          150
3   Mustang           80
4  Mercedes          200
5    Jaguar           90

Common columns...
Index([u'Car'], dtype='object')
raja
Published on 21-Sep-2021 08:23:20
Advertisements