Search code examples
pythonnumpyperformancenumba

Can I use numba to speed up this for cycle?


I came across numba, which is a fantastic library to speed up python code. I was wondering if is there any way to convert this code into numpy code to leverage on numba. My intention is , for each element of combination of OS_name and client cookie id, to find out what are the differences in each columns and record all the columns in which was shown at least one difference in a dictionary.

I tried doing :

@jit(nopython = True)
def gigi():
from tqdm.notebook import trange, tqdm
df = df.applymap(str)

df2 = df.copy()
del df2['client_cookie_id']


s = []
d = {}

for c in tqdm(range(0, len(df.client_cookie_id.unique().tolist()))):

    cid = df.client_cookie_id.unique().tolist()[c]

    for OS in df.OS_name.unique().tolist():

        ### take the indexes of all the occurrences of a single client_cookie_id

        t = df[(df['client_cookie_id'] == cid) & (df['OS_name'] == OS)].index.tolist()

        if len(t) >= 2:

            A = t[0]

            for i in t[1:]:


                B = i

                list1 = list(df2.loc[A])
                list2 = list(df2.loc[B])

                common = list(dict.fromkeys([l1 for l1 in list1 if l1 in list2]))
                remaining = list(filter(lambda i: i not in common, list1+list2))

                t1 = []

                for i in range(0, len(remaining)):

                    t1.append(remaining[i].split('___')[0])

                used = set()
                unique = [x for x in t1 if x not in used and (used.add(x) or True)]
                unique

                for i in range(0, len(unique)):

                    s.append(unique[i])

            s = [x for x in s if x not in used and (used.add(x) or True)]

        d[cid] = s

    else:

        continue

return d

gigi()

d = gigi()

But I receive the following error

AssertionError: Failed in nopython mode pipeline (step: inline calls to locally defined closures)
key already in dictionary: '$phi28.0'

Is someone able to help me? Thanks


Solution

  • This doesn't solve your whole problem, but it does show a much quicker way to scan through the rows. Note that I'm only printing the mismatches here; I'm not gathering them. Not sure what you wanted for an exact output:

    import pandas as pd
    
    data = { 
            'client_cookie_id': [ 111, 111, 111, 222, 222, 222 ],
            'OS_name': [ 333, 333, 444, 555, 555, 666 ],
            'data1': [ 21, 22, 23, 24, 25, 26 ],
            'data2': [ 31, 31, 31, 32, 33, 33 ]
        }
    
    
    def gigi(df):
        df = df.applymap(str)
        df = df.sort_values( by=['client_cookie_id', 'OS_name'] )
    
        last = None
        for index, row in df.iterrows():
            if last is not None and row['client_cookie_id'] == last['client_cookie_id'] and row['OS_name'] == last['OS_name']:
                # Compare the other columns.
                for name,b,c in zip(row.index, row, last):
                    if name not in ('client_cookie_id', 'OS_name') and b != c:
                        print("Difference in", name, 
                            "with", row['client_cookie_id'], '/', 
                            row['OS_name'], ": ", b, c )
            else:
                last = row
    
    df = pd.DataFrame(data)
    gigi(df)
    

    Output:

    Difference in data1 with 111 / 333 :  22 21
    Difference in data1 with 222 / 555 :  25 24
    Difference in data2 with 222 / 555 :  33 32