简体   繁体   English

Python3:如何用一维数组填充 5x5 个矩阵?

[英]Python3: How can I fill a 5x5 ones matrix with a one dimension array?

I have a 5x5 ones matrix:我有一个 5x5 个矩阵:

[[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?我可以在 python 中做什么?

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. repeat是制作多个副本的快速方法。 And since you are "filling" two rows at a time, let's apply the repeat to the 1d array - expanded to 2d:由于您一次“填充”两行,让我们将重复应用于 1d 数组 - 扩展为 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 :即使我们ones填充路线,使用 10 列最简单:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM