简体   繁体   中英

getting indices of non-unique items in an array

Given an integer array I with 0 <= I[j] < 1000 , with non-unique integer values I[j] , and a 'values' array V with V.shape == (1000, ) , how can I create an array R with R.shape == I.shape such that R[j] == V[I[j]] if I[j] is unique in I , and R[j] == np.nan if the value of I[j] occurs more than once in I ?

EDIT As an example, given I = np.array([1, 2, 1, 3, 2], dtype=int) , the result should be V = array([nan, nan, nan, V[3], nan]) , as 3 is the only unique element of I .

i = np.array([1, 2, 1, 3, 2], dtype=int)
v = np.random.rand(1000)

r = np.empty(shape=i.shape, dtype=v.dtype)
r.fill(np.nan)

unique, _ = np.unique(i, return_inverse=True)
counts = np.bincount(_)
r[unique[counts == 1]] = v[unique[counts == 1]]

>>> r
array([       nan,        nan,        nan,  0.5650245,        nan])

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