user11509999
user11509999

Reputation:

How to compare two dataframe columns(same data not required)?

I want to compare if the columns of two dfs are same not the data/Values

df1

         A       B       

    0   45      25

    1   46      26

    2   47      27

df 2

        B       A       

    0   45      25

    1   46      26

    2   47      27

I just want to check if both dfs have same columns and not data

I have tried to convert into list and series objects and then compare Its giving me

    ValueError: Can only compare identically-labeled dataframe objects 

Upvotes: 3

Views: 57

Answers (2)

Andy L.
Andy L.

Reputation: 25259

Try this:

df1.columns.difference(df2.columns).size == 0

Upvotes: 0

Adam.Er8
Adam.Er8

Reputation: 13403

you can get column names into a set and compare the sets:

print(set(df1.columns) == set(df2.columns))

Full example:

import pandas as pd
from io import StringIO


df1 = pd.read_csv(StringIO("""
         A       B       

    0   45      25

    1   46      26

    2   47      27"""), sep="\s+")

df2 = pd.read_csv(StringIO("""
        B       A       

    0   45      25

    1   46      26

    2   47      27"""), sep="\s+")

print(set(df1.columns) == set(df2.columns))

Output:

True

Upvotes: 1

Related Questions