pythonarraysnumpyappendvstack

append numpy arrays in a loop to an empty numpy array


I have an empty numpy array. And I want to append arrays to it such that each appended array becomes an element.

import numpy as np

a = np.array([])

for i in range(3):
    a=np.append(a,np.array(['x','y','z']))

print(a)

My expected outcome is : a= [['x','y','z'],['x','y','z'],['x','y','z']] but this seems to be impossible without adding axis=1 and handling the first append differently. This adds to unnecessary if condition every time in loop. Same is the problem while using vstack also. The first insert to the array has to happen with a hstack and the subsequent ones with a vstack.

What is the best way to achieve this in numpy?

TIA :)


Solution

  • You should not use any method of concatenating arrays repeatedly. Each concatenation will create a brand new array, which is a huge waste of time and space.

    The best practice should be to create an array list and then use a single stack to build the target array:

    >>> np.vstack([np.array(['x','y','z']) for _ in range(3)])
    array([['x', 'y', 'z'],
           ['x', 'y', 'z'],
           ['x', 'y', 'z']], dtype='<U1')
    

    Some other construction methods for this example:

    >>> np.tile(np.array(['x', 'y', 'z']), (3, 1))
    array([['x', 'y', 'z'],
           ['x', 'y', 'z'],
           ['x', 'y', 'z']], dtype='<U1')
    >>> np.array(['x','y','z'])[None].repeat(3, 0)
    array([['x', 'y', 'z'],
           ['x', 'y', 'z'],
           ['x', 'y', 'z']], dtype='<U1')