James Hayek
James Hayek

Reputation: 653

Python Numpy: Insert Data from 1D array into 2D array

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

Upvotes: 1

Views: 779

Answers (3)

Aubergine
Aubergine

Reputation: 407

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

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150805

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

How about:

twoD_Array.ravel()[:] = oneD_Array

Upvotes: 1

Amin Rashidbeigi
Amin Rashidbeigi

Reputation: 684

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

Upvotes: 3

Related Questions