1

In my codes, I created a list with n np.arrays with various length.

Sample of how to create the list:

MyArr = [None] * n
for l in range(n):
    MyArr[l] = np.array([1, 2, 3])   # Example 1
    # MyArr[l] = np.array([-1, -10])   # Example 2 

What I eventually want to do is make MyArr an 1D numeric array, like the following:

MyArr = [np.array([1, 2, 3]), np.array([1, 2]), np.array([10]), np.array([-1, -2, -3])]

Into:

np.array([1, 2, 3, 1, 2, 10, -1, -2, -3])

Because n is pretty large, I think using a for loop is not a good idea. What do you guys think?

3
  • It appears numpy.flatten will do the trick. Commented Feb 22, 2021 at 7:15
  • @bicarlsen flatten is a method, so you can apply it on MyArr but on nd-array. So its not whats needed in this case. Commented Feb 22, 2021 at 7:25
  • Just exactly how large is "pretty large"? Commented Feb 22, 2021 at 7:26

2 Answers 2

1

numpy's concatenate function may help:

np.concatenate([arr_1, arr_2, arr_3])
Sign up to request clarification or add additional context in comments.

Comments

0

First, there is an issue with the for loop that build MyArr. Notice that you override the lth element because you set it twice in 1 iteration.

Second, to flatten the list of numpy arrays you could use np.hstack in the following way:

l = [np.array([1,2,3]), np.array([-1,10])]
np.hstack(l)

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.