Search code examples
pandasdataframenames

Map column names if data is same in two dataframes


I have two pandas dataframes

df1 = A B C 1 2 3 2 3 4 3 4 5

df2 = X Y Z 1 2 3 2 3 4 3 4 5 I need to map based on data If data is same then map column namesenter code here Output = col1 col2 A X B Y C Z


Solution

  • I cannot find any built-in function to support this, hence simply loop over all columns:

    pairs = []
    for col1 in df1.columns:
        for col2 in df2.columns:
            if df1[col1].equals(df2[col2]):
                pairs.append((col1, col2))
    
    output = pandas.DataFrame(pairs, columns=['col1', 'col2'])