重复一个numpy数组N次

2024-03-28 20:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

hii专家我有一个1d numpy阵列,我想垂直重复3次

my_input_array = [-1.02295637 -0.60583836 -0.42240581 -0.78376377 -0.85821456]

我尝试了下面的代码

import numpy as np
x=np.loadtxt(my_input_array)
x.concatenate()

但是我得到了错误…通过这种方式…希望我能得到一些解决方案。谢谢

我的预期输出应如下所示

 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 -1.02295637
 -0.60583836
 -0.42240581
 -0.78376377
 -0.85821456
 

Tags: 代码importnumpyinputmyas错误np
3条回答

这就是你想要的:

x=np.concatenate([my_input_array, my_input_array, my_input_array])
for i in x:
    print(i)

输出:

-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456

^{}

np.tile(my_input_array, 3)

输出

array([-1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456,
       -1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456,
       -1.02295637, -0.60583836, -0.42240581, -0.78376377, -0.85821456])

编辑:刚刚注意到@hpaulj的答案。我仍然会留下我的答案,但他首先提到了np.tile

只需使用tile方法将给定形状的数组相乘,然后使用reshape方法构造它。使用x.shape[0]*x.shape[1]将其更改为列向量,而不显式给出形状维度

x=np.tile(x,(3,1))
y=x.reshape(x.shape[0]*x.shape[1])

相关问题 更多 >