Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

df.compare() how to change self/other labels with align_axis=1?

If I have two dataframes, then since pandas 1.1.0 I can compare them along axis 1 as follows:

import pandas as pd

df1 = pd.DataFrame([[1,2,3,4], [1,2,3,4]], index=['A', 'B'])
df2 = pd.DataFrame([[1,2,5,4], [5,2,3,1]], index=['A', 'B'])

df1.compare(df2, align_axis=1)

enter image description here

I would like to rename the self/other labels to something more descriptive.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am aware of this answer for the align_axis=0 case:

df1.compare(df2, align_axis=0).rename(index={'self': 'left', 'other': 'right'}, level=-1)

enter image description here

But that doesn’t work for align_axis=1:

df1.compare(df2, align_axis=1).rename(index={'self': 'left', 'other': 'right'}, level=-1)

enter image description here

(I also tried with level=0).

I am also aware of this open pull request that would add a suffixes argument to pd.compare that would allow you to do:

df1.compare(df2, align_axis=1, suffixes=["left", "right"])

but until that pull request gets merged, what is the way to currently do this in pandas?

>Solution :

When is axis 1 you should change index to columns in rename

df1.compare(df2, align_axis=1).rename(columns={'self': 'left', 'other': 'right'}, level=-1)
Out[56]: 
     0          2          3      
  left right left right left right
A  NaN   NaN  3.0   5.0  NaN   NaN
B  1.0   5.0  NaN   NaN  4.0   1.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading