2

Let's say we have a numpy array like this: array([{'k': 1}, {'k': 2}, {'k': 3}]) Is is possible to filter filter out only the elements that fulfill a certain condition? For example return only the dictionaries whose keys are > 1. Something like filter() function with lambda. I was looking into numpy.where() but I can't figure out the proper syntax.

1 Answer 1

2

There's nothing special related to numpy here, just

a = [{'k': 1}, {'k': 2}, {'k': 3}]
b = list(filter(lambda dic: dic['k'] > 1, a))

would work.

a = numpy.array([{'k': 1}, {'k': 2}, {'k': 3}])
b = numpy.array(list( filter(lambda dic: dic['k'] > 1, a) ) )

should work just as well.

Point is that you don't get any advantages of numpy if your array is onedimensional and you remove elements – Python's list is perfectly capable of that.

(assuming Python3, here, by the way.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that's what I thought. I will try to use different data structure instead of dict then.
If you know that your array elements always going to have a fixed set of keys, why not simply a 2d array?
That's not exactly the real life case I have but yeah, I will use a multidimensional arrays, thanks!

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.