简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM