I am trying to translate every element of a numpy.array
according to a given key:
For example:
a = np.array([[1,2,3], [3,2,4]]) my_dict = {1:23, 2:34, 3:36, 4:45}
I want to get:
array([[ 23., 34., 36.], [ 36., 34., 45.]])
I can see how to do it with a loop:
def loop_translate(a, my_dict): new_a = np.empty(a.shape) for i,row in enumerate(a): new_a[i,:] = map(my_dict.get, row) return new_a
Is there a more efficient and/or pure numpy way?
Edit:
I timed it, and np.vectorize
method proposed by DSM is considerably faster for larger arrays:
In [13]: def loop_translate(a, my_dict): ....: new_a = np.empty(a.shape) ....: for i,row in enumerate(a): ....: new_a[i,:] = map(my_dict.get, row) ....: return new_a ....: In [14]: def vec_translate(a, my_dict): ....: return np.vectorize(my_dict.__getitem__)(a) ....: In [15]: a = np.random.randint(1,5, (4,5)) In [16]: a Out[16]: array([[2, 4, 3, 1, 1], [2, 4, 3, 2, 4], [4, 2, 1, 3, 1], [2, 4, 3, 4, 1]]) In [17]: %timeit loop_translate(a, my_dict) 10000 loops, best of 3: 77.9 us per loop In [18]: %timeit vec_translate(a, my_dict) 10000 loops, best of 3: 70.5 us per loop In [19]: a = np.random.randint(1, 5, (500,500)) In [20]: %timeit loop_translate(a, my_dict) 1 loops, best of 3: 298 ms per loop In [21]: %timeit vec_translate(a, my_dict) 10 loops, best of 3: 37.6 ms per loop In [22]: %timeit loop_translate(a, my_dict)
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.
The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension.
To modify the data type of a NumPy array, use the astype(data type) method. It is a popular function in Python used to modify the dtype of the NumPy array we've been provided with. We'll use the numpy. astype() function to modify the dtype of the specified array object.
I don't know about efficient, but you could use np.vectorize
on the .get
method of dictionaries:
>>> a = np.array([[1,2,3], [3,2,4]]) >>> my_dict = {1:23, 2:34, 3:36, 4:45} >>> np.vectorize(my_dict.get)(a) array([[23, 34, 36], [36, 34, 45]])
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