1

I have a python list which contains numpy arrays like:

a = [Numpy array 1, Numpy array 2, Numpy array 3]

These Numpy arrays are all 2D numpy arrays.

Now if i pick any two Numpy arrays from my list 'a' randomly and make a tuple, say,

b = (Numpy array 1, Numpy array 2)

How can i detect which arrays were picked i.e.

Numpy array 1, Numpy array 2

and which weren't i.e

Numpy array 3?

Let me repharse my question: Which numpy array from my list 'a' is not present in the tuple 'b'?

2
  • Why are you using a list? Do the arrays have different shape? Commented Mar 21, 2019 at 14:36
  • You could perhaps store the numpy arrays within a dict? That way you can assign a key to the array and maybe give away with the tuple? Commented Mar 21, 2019 at 14:47

1 Answer 1

1

You can do that by converting the numpy array to a list. Let's imagine this is your a and b:

import random
a = [np.arange(10).reshape(2,5), np.arange(10,20), np.arange(20,30)] # list of numpy arrays
first = random.randint(0,2)
second = first
while second==first:
    second = random.randint(0,2)
b = (a[first],a[second])

Now we want to know which element of a is not in the tuple b. You first convert the numpy arrays of b to list. Then you can check it with the elements of a which are also converted to list:

def arrayinList(arr, listOfArray):
    return next((True for elem in listOfArray if np.array_equal(elem, arr)), False)

missing_elem = [elem for elem in a if not arrayinList(elem,b) ]
print(missing_elem)
Sign up to request clarification or add additional context in comments.

5 Comments

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() this error is being thrown by this line: missing_elem = [elem for elem in i if list(elem) not in list_b]
@AbdullahAjmal what is i in your code? And have you defined list_b as the above code? The code I have written is tested dozen of times and runs without any error. I guess that you have not defined list_b as the above code. First copy the code in my answer and run it. It should run correctly. After that check what you have programmed differently.
Your code is working fine. And i am editing your code exactly as above i.e Replacing your a and b accordingly to my a and b. But error still exists. I think the problem is 2D arrays? My numpy arrays are 2D arrays. While your arrays are 1D.
@AbdullahAjmal You are correct. I was assuming that your arrays are one dimensional. I have changed the code to also work for a list of arrays with different dimensions.
yeah it works now. That's exactly what i wanted. thank you so much.

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.