pythonnumpy-ndarray

Modify numpy array of arrays


I have a numpy array of numpy arrays and I need to add a leading zero to each of the inner arrays:

a = [[1 2] [3 4] [5 6]] --> b = [[0 1 2] [0 3 4] [0 5 6]]

Looping through like this:

for item in a:

item = np.insert(item, 0, 0)

doesn't help.

Numpy.put() flattens the array, which I don't want.

Any suggestions how I accomplish this? Thanks


Solution

  • np.insert - insert values along the given axis before the given indices. If axis is None then array is flattened first.

    import numpy as np
    
    a = np.array([[1, 2], [3, 4], [5, 6]])
    b = np.insert(a, 0, 0, axis=1)
    print(b)
    

    Result:

    [[0 1 2]
     [0 3 4]
     [0 5 6]]