python - Obtaining a numpy array from an array acting on a dictionary -
i want have array act on dictionary , return me corresponding values. rather loop through nice in pythonic way ie like
results[:] = dict[np_vec[:]]
that doesn't work though, hoping maybe there method i'm not aware of?
in case np_vec has integers correspond key in dict, while values tuples , want have list of them in results.
the straight forward pythonic (i.e. uses python syntax) method is
results = [dict[value] value in np_vec] this needs refinement if dict might not have value.
can use list comprehension on list of dictionaries if key missing?
but perhaps hoping passes vectorized numpy expression. sticking point dictionary access 1 key @ time
another possibility use dict.keys() list of keys, , use numpy methods match np_vec list. no guarantee faster.
in1d doc
> in1d(a, b) equivalent np.array([item in b item in a]). i'm thinking of (but details may off)
keys = dict.keys() values = dict.values() mask = np.in1d(dict.keys(), np_vec) result = values[mask] working code using arrays:
a dictionary numeric keys, tuple values:
in [302]: adict={k:v k,v in zip([0,1,2,3,4,5],[(0,1),(1,2),(2,3),(3,4),(4,5)])} in [303]: adict out[303]: {0: (0, 1), 1: (1, 2), 2: (2, 3), 3: (3, 4), 4: (4, 5)} array of keys want fetch
in [304]: npvec=np.arange(4) lists dictionary:
in [305]: keys=list(adict.keys()) in [308]: values=list(adict.values()) in [309]: values out[309]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] mask - keys want pull
in [310]: mask=np.in1d(keys,npvec) in [311]: mask out[311]: array([ true, true, true, true, false], dtype=bool) to apply mask in 1 step, have use array; keys[mask] not work:
in [313]: np.array(keys)[mask] out[313]: array([0, 1, 2, 3]) the same work if values simple numbers, tuples.
in [314]: np.array(values)[mask] out[314]: array([[0, 1], [1, 2], [2, 3], [3, 4]]) we turn 2d array list of tuples.
but preserve tuples (or other general python object values), have more complicated, e.g.
in [315]: varray=np.empty(len(values),dtype=object) in [317]: in range(5):varray[i]=values[i] in [318]: varray out[318]: array([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)], dtype=object) now can apply mask , right set of values.
in [319]: varray[mask] out[319]: array([(0, 1), (1, 2), (2, 3), (3, 4)], dtype=object) contrast simple list comprehension solution:
in [321]: [adict[v] v in npvec] out[321]: [(0, 1), (1, 2), (2, 3), (3, 4)] sometimes trying more pythonic, err numpy-onic, isn't worth work.
Comments
Post a Comment