Compare two Excel files that have a different number of rows using Python Pandas

Viewed 5437

I'm using Python 3.7 , and I want to compare two Excel file that have the same columns (140 columns) but with a different number of rows, I looked on the website , but I didn't find a solution for my case!

Here is an example :

df1 (old report) : 

id       qte     d1    d2

A        10      23    35  

B        43      63    63

C       15       61    62

df2 (new report) : 

id       qte     d1    d2

A        20      23    35  

C       15       61    62

E       38       62    16

F       63       20    51

and the results should be :

  • the modify rows must be in yellow and the value modified in red color

  • the new rows in green

  • the deleted rows in red

    id qte d1 d2

    A 20 23 35

    C 15 61 62

    B 43 63 63

    E 38 62 16

    F 63 20 51

the code :

import pandas as pd
import numpy as np

df1= pd.read_excel(r'C .....\data novembre.xlsx','Sheet1',na_values=['NA'])
df2= pd.read_excel(r'C.....\data decembre.xlsx','Sheet1',na_values=['NA'])
merged_data=df1.merge(df2, left_on = 'id', right_on = 'id', how = 'outer')

Joining the data though is not want I want to have!

I'm just starting to learn Python so I really need help!

1 Answers

an excel diff can quickly become a funky beast, but we should be able to do this with some concats and boolean statements.

assuming your dataframes are called df1, df2

df1 = df1.set_index('id')
df2 = df2.set_index('id')

df3 = pd.concat([df1,df2],sort=False)
df3a = df3.stack().groupby(level=[0,1]).unique().unstack(1).copy()


df3a.loc[~df3a.index.isin(df2.index),'status'] = 'deleted' # if not in df2 index then deleted
df3a.loc[~df3a.index.isin(df1.index),'status'] = 'new'     # if not in df1 index then new
idx = df3.stack().groupby(level=[0,1]).nunique() # get modified cells. 
df3a.loc[idx.mask(idx <= 1).dropna().index.get_level_values(0),'status'] = 'modified'
df3a['status'] = df3a['status'].fillna('same') # assume that anything not fufilled by above rules is the same.

print(df3a)

      d1    d2       qte    status
id                                
A   [23]  [35]  [10, 20]  modified
B   [63]  [63]      [43]   deleted
C   [61]  [62]      [15]      same
E   [62]  [16]      [38]       new
F   [20]  [51]      [63]       new

if you don't mind the performance hit of turning all your datatypes to strings then this could work. I dont' recommend it though, use a fact or slow changing dimension schema to hold such data, you'll thank your self in the future.

df3a.stack().explode().astype(str).groupby(level=[0,1]).agg('-->'.join).unstack(1)

    d1  d2      qte    status
id                           
A   23  35  10-->20  modified
B   63  63       43   deleted
C   61  62       15      same
E   62  16       38       new
F   20  51       63       new
Related