Are there good ways to “expand” a numpy ndarray? Say I have an ndarray like this:
[[1 2]
[3 4]]
And I want each row to contains more elements by filling zeros:
[[1 2 0 0 0]
[3 4 0 0 0]]
I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements from old smaller arrays), just wondering are there pythonic ways to do so. Tried numpy.reshape but didn’t work:
import numpy as np
a = np.array([[1, 2], [3, 4]])
np.reshape(a, (2, 5))
Numpy complains that: ValueError: total size of new array must be unchanged
There are the index tricks
r_andc_.If this is performance critical code, you might prefer to use the equivalent
np.concatenaterather than the index tricks.There are also
np.resizeandnp.ndarray.resize, but they have some limitations (due to the way numpy lays out data in memory) so read the docstring on those ones. You will probably find that simply concatenating is better.By the way, when I’ve needed to do this I usually just do it the basic way you’ve already mentioned (create an array of zeros and assign the smaller array inside it), I don’t see anything wrong with that!