pythonarraysnumpy

loss of dimentionality of numpy array


i have writen the following test code

import numpy

first = numpy.array([[0,0]])
print(first)
temp = numpy.array([1,1])
first = numpy.insert(first, 0, temp)
print(first)
first = first[:-1]
print(first)

the intent for the code is to generate an array of arrays then insert an additional array and then remove the last array in the set

but after inserting the new array, then the original array converts from an array of arrays, to an array of numbers, so removing the last entry results in only removing the last number.

any idear how to fix?


Solution

  • Then you need to specify axis

    first = numpy.insert(first, 0, temp, 0)
    #array([[1, 1],
    #       [0, 0]])
    

    If you don't, as the documentation says

    axis: int, optional

    Axis along which to insert values. If axis is None then arr is flattened first.

    So, as is, your code starts with turning first into [0,0], then inserts values 1,1 at position 0 of that flattened array.

    If you specify axis 0, then, as I believe you want, first is considered to be an array of arrays, and you insert at position 0 of this array of array a new array.