Home > Mobile >  Finding instances similar in two lists with the same shape
Finding instances similar in two lists with the same shape

Time:06-10

So I am working with a timeseries data. But to simplify the question, let's say I have two lists of equal shape but then I need to find instances like when 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] So we can see that in about four positions, both lists have numbers greater than 0, there are other instances I also would like to find, 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.

CodePudding user response:

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]

CodePudding user response:

If you want to use vanilla python, this should be doing what you are looking for

l = 0
for i in range(len(A)):
    if A[i] > 0 and B[i] > 0:
        l = l   1

  • Related