Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting pandas column name based on bool mask

Tags:

python

pandas

I have two dataframes, df1 and df2, where one value is changed in df2. I'm trying to get the column name for the value that changed.

df1

    type method
0  variable   method1
1  variable   method1
2  variable   method1
3  variable   method1

df2

        type method
0    variable   method1
1    variable   method1
2    variable   method1
3  timeseries   method1

find the changes:

changes = df1.ne(df2)

changes:

    type  method
0  False   False
1  False   False
2  False   False
3   True   False

How would you get the column name for the column that changed?

like image 306
2083 Avatar asked Mar 04 '23 16:03

2083


1 Answers

Use DataFrame.any for test at least one True per column and then filter columns names:

print (changes.any())
type       True
method    False
dtype: bool

print (changes.columns[changes.any()])
Index(['type'], dtype='object')
like image 116
jezrael Avatar answered Mar 08 '23 18:03

jezrael