1

I am trying to insert data from a 1D array into a 2D array and still maintain the shape from the 2D array.

My code below reformats the 2D array into 1D. Also, why do I now have 26 indexes? What am I missing?

import numpy as np

oneD_Array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                      15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25])

twoD_Array = np.zeros((5, 5))

print(oneD_Array.shape)
print(oneD_Array)
print()
print()
print(twoD_Array.shape)
print(twoD_Array)

for i in range(len(oneD_Array), -1, -1):
    # for subArray in twoD_Array:
    twoD_Array = np.insert(oneD_Array, 0, [i])

print()
print(twoD_Array)
print(twoD_Array.shape)

The output is:

(25,)
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 25]


(5, 5)
[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25]
(26,)

3 Answers 3

3

You simply can use np.reshape:

twoD_Array = np.reshape(oneD_Array, (5, 5))

output:

array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])
Sign up to request clarification or add additional context in comments.

2 Comments

This would work too, although, I'm not sure which is better given varying situations.
There is some comparison: stackoverflow.com/a/33118119/5714900
1

because np.insert actually inserts an element to the array at the given index.

How about:

twoD_Array.ravel()[:] = oneD_Array

1 Comment

I'm still fresh at this and didn't know .ravel, I will read more into this. Your proposed solution works.
1

If you insist on using a loop, it could be written like this:

for i in range(len(oneD_Array)):
    twoD_Array[i//twoD_Array.shape[1], i%twoD_Array.shape[1]] = oneD_Array[i]

But it's definitely not the fastest way.

On my machine, for a 500x500 array, my loop takes 85 ms, using ndarray.ravel takes 223 µs, using np.reshape takes 1.17 µs and using ndarray.reshape takes 357 ns. So I would go with

twoD_Array = oneD_Array.reshape((5, 5))

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.