Good ways to “expand” a numpy ndarray?

后端 未结 6 670
一个人的身影
一个人的身影 2020-12-04 16:43

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 ele

6条回答
  •  一个人的身影
    2020-12-04 17:02

    Just to be clear: there's no "good" way to extend a NumPy array, as NumPy arrays are not expandable. Once the array is defined, the space it occupies in memory, a combination of the number of its elements and the size of each element, is fixed and cannot be changed. The only thing you can do is to create a new array and replace some of its elements by the elements of the original array.

    A lot of functions are available for convenience (the np.concatenate function and its np.*stack shortcuts, the np.column_stack, the indexes routines np.r_ and np.c_...), but there are just that: convenience functions. Some of them are optimized at the C level (the np.concatenate and others, I think), some are not.

    Note that there's nothing at all with your initial suggestion of creating a large array 'by hand' (possibly filled with zeros) and filling it yourself with your initial array. It might be more readable that more complicated solutions.

提交回复
热议问题