1 Upvote

Find Matched & Unmatched Column Names Between Two Dataframes

Python
Data Preprocessing

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. Matched Columns
df_1_cols = set(df_1.columns)
matched_columns = [x for x in df_2.columns if x in df_1_cols]

# 2. Unmatched Columns in df_2 compared to df_1
df_1_cols = set(df_1.columns)
unmatched_columns = [x for x in df_2.columns if x not in df_1_cols]

# 3. Unmatched Columns in df_1 compared to df_2
df_1_cols = set(df_1.columns)
unmatched_columns = [x for x in df_2.columns if x not in df_1_cols]

By detro - Last Updated June 4, 2022, 6:04 p.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3
2
Top Contributors
103
100