python - Numpy Lookup (Map, or Point) -
i have large numpy array:
array([[32, 32, 99, 9, 45], # [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]])
and large-ish array of unique values in particular order:
array([ 99, 32, 45, 9]) # b
how can (no python dictionaries, no copies of a
, no python loops) replace values in a
become indicies of values in b
?:
array([[1, 1, 0, 3, 2], [0, 2, 3, 2, 1], [2, 2, 0, 0, 1], [3, 3, 1, 2, 0]])
i feel reaaly dumb not being able off top of head, nor find in documentation. easy points!
here go
a = array([[32, 32, 99, 9, 45], # [99, 45, 9, 45, 32], [45, 45, 99, 99, 32], [ 9, 9, 32, 45, 99]]) b = array([ 99, 32, 45, 9]) ii = np.argsort(b) c = np.digitize(a.reshape(-1,),np.sort(b)) - 1
originally suggested:
d = np.choose(c,ii).reshape(a.shape)
but realized that had limitations when went larger arrays. instead, borrowing @unutbu's clever reply:
d = np.argsort(b)[c].reshape(a.shape)
or one-liner
np.argsort(b)[np.digitize(a.reshape(-1,),np.sort(b)) - 1].reshape(a.shape)
which found faster or slower @unutbu's code depending on size of arrays under consideration , number of unique values.
Comments
Post a Comment