0

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 :)

3
  • 1
    best is not to do any of this in a loop. You are trying imitate a list method. Stick with lists. Commented Apr 29, 2023 at 14:17
  • elaborate "handling the first append differently", how those subarrays differ? Commented Apr 29, 2023 at 14:20
  • 1
    But if you insist, You have to start with a correct shaped a, like (0,3) shape. And add a (1,3) shape each loop. And make sure each has the correct dtype. And use axis=0. The goal is a (n,3) array. Keep that in mind. Commented Apr 29, 2023 at 14:24

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.