Find Matched & Unmatched Column Names Between Two Dataframes

Python

In this code snippet we compare the column names of two dataframes: df_1 and df_2. First we get a list of all columns that are the same, then a list of all unmatched columns in df_2 compared to df_1 and finally a list of all unmatched columns in df_1 compared to df_2.

 1|  # 1. Matched Columns
 2|  df_1_cols = set(df_1.columns)
 3|  matched_columns = [x for x in df_2.columns if x in df_1_cols]
 4|  
 5|  # 2. Unmatched Columns in df_2 compared to df_1
 6|  df_1_cols = set(df_1.columns)
 7|  unmatched_columns = [x for x in df_2.columns if x not in df_1_cols]
 8|  
 9|  # 3. Unmatched Columns in df_1 compared to df_2
10|  df_1_cols = set(df_1.columns)
11|  unmatched_columns = [x for x in df_2.columns if x not in df_1_cols]
Did you find this snippet useful?

Sign up for free to to add this to your code library