Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do this array lookup/replace with numpy?

Tags:

python

numpy

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]])
like image 724
ajwood Avatar asked Nov 18 '11 20:11

ajwood


People also ask

How do you replace an array value in Python?

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.

How do I turn an array into a NumPy array?

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.

What is a correct method to search for a certain value in a NumPy array?

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.

What is NumPy Column_stack () used for?

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.


1 Answers

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]])
like image 81
JoshAdel Avatar answered Oct 14 '22 06:10

JoshAdel