Search code examples
pythonlistnumpymathmultiple-instances

Finding instances similar in two lists with the same shape


I am working with a timeseries data. Let's say I have two lists of equal shape and I need to find instances where both lists have numbers greater than zero at the same position.

To break it down

A = [1,0,2,0,4,6,0,5]
B = [0,0,5,6,7,5,0,2]

We can see that in four positions, both lists have numbers greater than 0. There are other instances , but I am sure if I can get a simple code, all it needs is adjusting the signs and I can also utilize in a larger scale.

I have tried

len([1 for i in A if i > 0 and 1 for i in B if i > 0 ])

But I think the answer it's giving me is a product of both instances instead.


Solution

  • Since you have a tag:

    A = np.array([1,0,2,0,4,6,0,5])
    B = np.array([0,0,5,6,7,5,0,2])
    
    mask = ((A>0)&(B>0))
    # array([False, False,  True, False,  True,  True, False,  True])
    
    mask.sum()
    # 4
    
    A[mask]
    # array([2, 4, 6, 5])
    
    B[mask]
    # array([5, 7, 5, 2])
    

    In pure python (can be generalized to any number of lists):

    A = [1,0,2,0,4,6,0,5]
    B = [0,0,5,6,7,5,0,2]
    
    mask = [all(e>0 for e in x) for x in zip(A, B)]
    
    # [False, False, True, False, True, True, False, True]