0

For instance I have this list:

A = [(1, 2.5), (2, 5.0), (3, 7.5), (4, 10.0)]

and I have another list with the following entry:

B = [2.5, 7.5, 12.5]

What I want is a program in Python where if the 2nd element of each tuple in A, namely 2.5, 5.0, 7.5, and 10.0, can be found in B, it will create another variable which looks like this:

C = [(1, 2.5), (3, 7.5)]

where it removes the other tuples in A whose 2nd elements are not in B. I tried to code it this way:

A = [(1, 2.5), (2, 5.0), (3, 7.5), (4, 10.0)]
D = np.asarray(list(A))
E = []
if D[:, 1] in B:
    E = np.append(E,D)
else:
    pass

but I got an error of:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

2
  • Is 7,5 in B a typo for 7.5? Commented Jul 15, 2014 at 12:12
  • B is also never defined if D[:,1] in B: Commented Jul 15, 2014 at 12:14

2 Answers 2

2

You could use np.n1d to determine which values in A[:, 1] are also in B:

In [104]: A = np.array([(1,2.5), (2,5.0), (3,7.5), (4,10.0)])

In [105]: B = [2.5, 7.5, 12.5]

In [106]: mask = np.in1d(A[:, 1], B)

In [107]: mask
Out[107]: array([ True, False,  True, False], dtype=bool)

In [108]: A[mask]
Out[108]: 
array([[ 1. ,  2.5],
       [ 3. ,  7.5]])
Sign up to request clarification or add additional context in comments.

Comments

2

Why not simply the following:

>>> A = [(1,2.5), (2,5.0), (3,7.5), (4,10.0)]
>>> B = [2.5, 7,5, 12.5]
>>> C = [a for a in A if a[1] in B]
>>> C
[(1, 2.5), (3, 7.5)]

1 Comment

Because iterating in native Python - whether with a comprehension or a loop - usually defeats the purpose of Numpy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.