Skip to content Skip to sidebar Skip to footer

Multiply Two Arrays Element Wise, Where One Of The Arrays Has Arrays As Elements

I have the following situation in which I want to multiply two arrays element wise, where one of the arrays has arrays as elements: >>> import numpy as np >>> bas

Solution 1:

These two pieces of code produce different things, although the space has no effect:

>>> np.array([np.ones(3), np.ones(3)])
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

Because both arrays in your list have the same dimension, this is converted into a single array of 2 rows and 3 columns.

>>> np.array([np.ones(3), np.ones(7)])
array([array([ 1.,  1.,  1.]), array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.])], dtype=object)

In this case, the lengths of the arrays do not match, so numpy creates a 1D array, two items long, of type object and each of those objects happens to be a numpy array.

When you multiply the first with c, you are trying to multiply an array of shape (2, 3) with an array of shape (2,), something numpy does not know how to do. You could get what you want if you reshaped your c array to have shape (2, 1), e.g.

>>> grid_mod * c[:, np.newaxis]
array([[  9.,   9.,   9.],
       [ 11.,  11.,  11.]])

When you multiply the second with c, you are trying to multiply two arrays of shape (2,), so numpy does elementwise multiplication with no problems. And since each of the items of your array is itself an array, when you try to multiply it by a scalar, numpy also know how to do it. While this does work, it is much, much slower than the previous approach, about 100x for 10000 row arrays:

c = np.random.rand(10000)
a = np.random.rand(10000, 3)
b = np.empty((10000,), dtype=object)
for j in xrange(10000):
    b[j] = a[j]

%timeit a*c[:, np.newaxis]
10000 loops, best of 3: 176 us per loop

%timeit b*c
10 loops, best of 3: 16.5 ms per loop

Post a Comment for "Multiply Two Arrays Element Wise, Where One Of The Arrays Has Arrays As Elements"