I have a mx1 array, a, that contains some values. Moreover, I have a nxk array, say b, that contains indices between 0 and 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 I want to get the corresponding value from a. I can do it with a loop:
c = np.zeros_like(b).astype('float')
n, k = b.shape
for i in range(n):
for j in range(k):
c[i, j] = a[b[i, j]]
Is there any built-it numpy function or trick that is more elegant? This approach looks a little dumb to me. PS: originally, a and b are Pandas objects if that helps.
Method 3: Using array_equal() This array_equal() function checks if two arrays have the same elements and same shape.
How do you check if an array contains a value? The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.
Access Array ElementsYou can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
>>> a
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 just a[b]
. (Also, you probably wanted the upper bound on the randint
call to be 3
.)
Try iteration with a numpy.flatiter
object:
a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))
c = np.array([a[i] for i in b.flat]).reshape(b.shape)
print(c)
array([[ 0.2, 0.2, 0.2, 0.1],
[ 0.3, 0.3, 0.2, 0.1],
[ 0.2, 0.1, 0.3, 0.3],
[ 0.3, 0.3, 0.3, 0.1]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With