How to compare two rows in pandas/ python if they overlap

Viewed 44

I have data frame like below

     product        model   ci_low      ci_upp  

        A             X    0.041667    48.0 

        A             Y    0.000000    21.0 

I want to check if ci_low and ci_upp overlap by product and return something like

 product       CI Band X        CI Band Y         Overlap

       A      [0.041667-48.0]   [0.00000 - 21.0]    Yes

Note: I have function to check if range overlap, if it return 0 then they dont overlap

    def getOverlap(a, b):
          return max(0, min(a[1], b[1]) - max(a[0], b[0]))
1 Answers

First we need pivot and create the range index then use the overlap to find the intersection

df['Ci band']=pd.IntervalIndex.from_arrays(df.ci_low,df.ci_upp,closed='both')
s=df.pivot('product','model','Ci band').add_prefix('CI Band')
s['Overlap']=s.apply(lambda x : x['CI BandX'].overlaps(x['CI BandY']),axis=1)
s
Out[55]: 
model            CI BandX     CI BandY  Overlap
product                                        
A        [0.041667, 48.0]  [0.0, 21.0]     True
Related