To find the common elements in a Pandas DataFrame, we can use the merge() method with a list of columns
Steps
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1.
Print the input DataFrame, df1.
Create another two-dimensional tabular data, df2.
Print the input DataFrame, df2.
Find the common elements using merge() method.
Print the common DataFrame.
Example
import pandas as pd df1 = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) df2 = pd.DataFrame( { "x": [5, 2, 7, 0, 11, 12], "y": [4, 7, 5, 1, 19, 20], "z": [9, 3, 5, 1, 29, 30] } ) print("Input DataFrame 1 is:\n", df1) print("Input DataFrame 2 is:\n", df2) common = df1.merge(df2, on=['x', 'y', 'z']) print("Common of DataFrame 1 and 2 is: \n", common)
Output
Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Input DataFrame 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 11 19 29 5 12 20 30 Common of DataFrame 1 and 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1