Python3: How can I fill a 5×5 ones matrix with a one dimension array?

Question:

I have a 5×5 ones matrix:

[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

and I want to fill it with this one dimension array:

[0.72222515 1.25003225 0.11767353 0.16121767 0.27926356 0.78412963
 0.08371721 1.77536532 1.67636045 0.55364691]

like:

[[0.72222515 1.25003225 0.11767353 0.16121767 0.27926356]
 [0.78412963 0.08371721 1.77536532 1.67636045 0.55364691]
 [[0.72222515 1.25003225 0.11767353 0.16121767 0.27926356]
 [0.78412963 0.08371721 1.77536532 1.67636045 0.55364691]
[[0.72222515 1.25003225 0.11767353 0.16121767 0.27926356]

What can I do in python?

Asked By: Shuning

||

Answers:

Probably we can do that with a loop, like this… Not sure if this is the best way…

import numpy as np 

arr1 = np.ones((5,5))
arr2 = np.array([1,2,3,4,5,6,7,8,9,10])
arr2 = np.reshape(arr2, (-1, 5))

for i in range(0,len(arr1)):
    if i % 2 == 0:
        arr1[i] = arr2[0]
    else:
        arr1[i] = arr2[1]

# Output of arr1
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.],
       [ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.],
       [ 1.,  2.,  3.,  4.,  5.]])
Answered By: Sachin Kohli

Instead of filling an existing array, we could make a new array with the desired layout.

In [129]: arr = np.arange(10)

repeat is a fast way of making multiple copies. And since you are "filling" two rows at a time, let’s apply the repeat to the 1d array – expanded to 2d:

In [132]: arr[None,:].repeat(3,0)
Out[132]: 
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

Then reshape to the desired shape:

In [133]: arr[None,:].repeat(3,0).reshape(6,5)
Out[133]: 
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

And use slicing to get rid of the extra row:

In [134]: arr[None,:].repeat(3,0).reshape(6,5)[:5,:]
Out[134]: 
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4]])

Even if we go the fill route, it’s easiest to work with a 10 column ones:

In [135]: new = np.ones((3,10)); new[:] = arr    
In [136]: new
Out[136]: 
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])

In [137]: new.reshape(-1,5)[:5,:]
Out[137]: 
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.],
       [0., 1., 2., 3., 4.]])
Answered By: hpaulj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.