Reputation: 42329
I have to multiply two numpy
arrays of different sizes (a
and b
), but I need to discard the first element of b
before resizing.
What I see is that, if I use the full b
array the resizing has no issues (but the result is not what I need, since it contains the first element of b
). If I attempt to slice the first element off before applying resize
I get a
ValueError: cannot resize this array: it does not own its data
Why does this happen, and how can I get around this in the most efficient way possible?
import numpy as np
# Some data
a = np.random.uniform(0., 1., 17)
# Works
b = np.array([56, 7, 343, 89, 234])
b.resize(a.shape)
d = b * a
# Does not
b = np.array([56, 7, 343, 89, 234])[1:]
b.resize(a.shape)
d = b * a
Upvotes: 0
Views: 582
Reputation: 231385
Another option is to just do the multiplication for the terms that matter:
n = len(b)-1
d = np.zeros_like(a)
d[:n] = b[1:] * a[:n]
for:
In [628]: a.shape
Out[628]: (1000000,)
In [629]: b=np.arange(100)
this is 2x faster than (which time about the same)
b.resize(len(a)+1,); d = b[1:] * a
b1 = b[1:].copy(); b1.resize(len(a)); d = b1 * a
Relative timings can vary with the size of b
and a
. While resize can be done in place, it probably will require a new data buffer, especially if it pads with a lot of zeros.
Upvotes: 1
Reputation: 3706
the other order? pad out b
to one element longer b.resize((len(a)+1,))
then multiply d = b[1:] * a
b = np.array([56, 7, 343, 89, 234])
b.resize((len(a)+1,))
d = b[1:] * a
Upvotes: 1