python - Numpy: get values from array where indices are in another array -
i have mx1 array, a, contains values. moreover, have nxk array, b, contains indices between 0 , m.
example:
a = np.array((0.1, 0.2, 0.3)) b = np.random.randint(0, 3, (4, 4)) for every index value in b want corresponding value a. can loop:
c = np.zeros_like(b).astype('float') n, k = b.shape in range(n): j in range(k): c[i, j] = a[b[i, j]] is there built-it numpy function or trick more elegant? approach looks little dumb me. ps: originally, , b pandas objects if helps.
>>> array([ 0.1, 0.2, 0.3]) >>> b array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1]]) >>> a[b] array([[ 0.1, 0.1, 0.2, 0.2], [ 0.1, 0.1, 0.2, 0.2], [ 0.1, 0.2, 0.2, 0.1], [ 0.1, 0.2, 0.1, 0.2]])
tada! it's a[b]. (also, wanted upper bound on randint phone call 3.)
python numpy pandas
No comments:
Post a Comment