Home > Net >  NumPy: Can I create an array of just the values from an array of dicts?
NumPy: Can I create an array of just the values from an array of dicts?

Time:11-15

So I have a 2d array where each element is a dict, like so:

[[{"key":"value"},{"key":"othervalue"}],
[{"key":"notvalue"},{"key":"value"}]]

I'm trying to use that to make a second array, where each element is based on the value of the first array's dictionaries, so it would look something like this:

[[True, True]
[False, True]]

or even this:

[["value","othervalue"]
["notvalue","value"]]

But I cannot for the life of me figure out how to get at the values inside the dictionaries. Right now I'm doing this:

results=numpy.where((old_array=={"key":"value"}) | (old_array=={"key":"othervalue"}))
for i in zip(results[0], results[1]):
    new_array[i[0],i[1]]=True

...but I feel like there's got to be a better way than that. Is there some nice, neat function to use with arrays of dictionaries that I'm completely missing? Or is this just one I'm gonna have to clunk my way through?

Thanks in advance!

CodePudding user response:

In [263]: arr =np.array([[{"key":"value"},{"key":"othervalue"}],
     ...: [{"key":"notvalue"},{"key":"value"}]])
In [264]: arr
Out[264]: 
array([[{'key': 'value'}, {'key': 'othervalue'}],
       [{'key': 'notvalue'}, {'key': 'value'}]], dtype=object)

the straightforward list comprehension approach:

In [266]: [d['key'] for d in arr.ravel().tolist()]
Out[266]: ['value', 'othervalue', 'notvalue', 'value']

a pretty alternative, though not faster:

In [267]: np.frompyfunc(lambda d:d['key'],1,1)(arr)
Out[267]: 
array([['value', 'othervalue'],
       ['notvalue', 'value']], dtype=object)

Object dtype arrays are practically speaking lists, storing references, not special numpy objects. And dict can only be accessed by key indexing (or items/values). numpy does not add any special dict handling code.

  • Related