I've got a 2D numpy array, A
containing an index into another array, B
. What is a good way to get C
from A
and B
using numpy?
A = array([[1, 1, 0, 2],
[1, 0, 0, 2],
[1, 1, 0, 2]])
B = array([0, 5, 3])
C = array([[5, 5, 0, 3],
[5, 0, 0, 3],
[5, 5, 0, 3]])
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
Convert a list to a NumPy array: numpy. You can convert a list to a NumPy array by passing a list to numpy. array() . The data type dtype of generated numpy. ndarray is automatically determined from the original list but can also be specified with the dtype parameter.
You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.
column_stack() in Python. numpy. column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array.
How about this C = B[A]
. That's the beauty of numpy:
In [1]: import numpy as np
In [2]: A = np.array([[1, 1, 0, 2],
...: [1, 0, 0, 2],
...: [1, 1, 0, 2]])
In [3]: B = np.array([0, 5, 3])
In [4]: B[A]
Out[4]:
array([[5, 5, 0, 3],
[5, 0, 0, 3],
[5, 5, 0, 3]])
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