You are not logged in.

#1 2012-07-08 09:50:37

synthead
Member
Registered: 2006-05-09
Posts: 1,337

Python, numpy, values of dicts, and numpy.where

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

#2 2012-07-09 21:46:13

Lux Perpetua
Member
From: The Local Group
Registered: 2009-02-22
Posts: 73

Re: Python, numpy, values of dicts, and numpy.where

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

#3 2012-07-10 01:11:49

thisoldman
Member
From: Pittsburgh
Registered: 2009-04-25
Posts: 1,172

Re: Python, numpy, values of dicts, and numpy.where

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

Board footer

Powered by FluxBB