I have two Python lists,
presence. I want to do cross-tabulation and get the count for each block out of four, such as A, B, C, and D in the below code.
- Both the lists have values
- I have tried Pandas' crosstab function. However, it's slower than my code which is below.
- One problem with my code is it's not vectorized and is using a for loop which slows things down.
Could the below function in Python be made any faster?
def cross_tab(label,presence): A_token=0 B_token=0 C_token=0 D_token=0 for i,j in zip(list(label),list(presence)): if i==True and j==True: A_token+=1 elif i==False and j==False: D_token+=1 elif i==True and j==False: C_token+=1 elif i==False and j==True: B_token+=1 return A_token,B_token,C_token,D_token
Some sample data and example input and output.
##input label=[True,True,False,False,False,False,True,False,False,True,True,True,True,False] presence=[True,False,False,True,False,False,True,True,False,True,False,True,False,False] ##processing A,B,C,D=cross_tab(label,presence) print('A:',A,'B:',B,'C:',C,'D:',D) ##Output A: 4 B: 2 C: 3 D: 5
Edit: Answer provided by Maarten Fabre below is working perfectly. To anyone who will stumble here in future, the logic flow is as follows.
Goal: find a way for vectorization: Below are the solution steps
- Analyze and find unique value at each evaluation. This will help save logical output in single array.
- By multiplying 2 with any given array and adding resultant array with other array we can get results in single array with unique coded value for each logic.
- Get count of the unique element in array and fetch values.
- Since calculation can be done in arrays without loop, convert list into np array to allow vectorized implementation.