You are not logged in.
if I have a numpy.array value that is a dict, say, { 'this' : 'that' }, how can I use numpy.where() to return array coordinates for values that are a dict? Or even better, dicts with an index of 'this' in them? I'd much prefer to do this without a loop (at that would be very slow). Thanks!
Offline
One way to do this without a loop:
def myfunc(x):
return type(x) == dict and 'this' in x
myfuncv = numpy.frompyfunc(myfunc, 1, 1)
indices = numpy.where(myfuncv(some_array))
However, you're not likely to see a significant speed improvement over calling myfunc in a loop, since either way, you're still calling a Python function for every element of the array. Unfortunately, I don't see any way around this, since determining the type of an object and testing for a key in a dict are fundamentally Python operations. If you disagree, perhaps you should clarify your problem a bit and give some more context.
Offline
This doesn't get rid of loops but it's another solution that may give you some ideas.
>>> ugly_list = [{'this': 'that', 1: 'a', 0: 'b'}, 2, 'foo', {'z': 'b', 1: 'a', 'this': 'the other'}, 1, 'a', {1: 12}]
>>> list(map(str.upper, (x['this'] for x in (d for d in ugly_list if type(d) == dict) if 'this' in x)))
['THAT', 'THE OTHER']
Would you have to do nesting similar to the genexp above with numpy.where()?
Last edited by thisoldman (2012-07-10 01:12:53)
Offline