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.
Add a comment
|
1 Answer
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.)
3 Comments
Chris Koston
Thanks, that's what I thought. I will try to use different data structure instead of dict then.
Marcus Müller
If you know that your array elements always going to have a fixed set of keys, why not simply a 2d array?
Chris Koston
That's not exactly the real life case I have but yeah, I will use a multidimensional arrays, thanks!