引导numpy 2D阵列

2024-05-16 08:33:44 发布

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

我试着用行替换形状为(4,2)的base2dnumpy数组,比如10次。最终的输出应该是一个3D numpy数组。在

已经尝试了下面的代码,它是有效的。但是有没有办法不使用for循环来完成呢?在

base=np.array([[20,30],[50,60],[70,80],[10,30]])
print(np.shape(base))
nsample=10
tmp=np.zeros((np.shape(base)[0],np.shape(base)[1],10))
for i in range(nsample):
    id_pick = np.random.choice(np.shape(base)[0], size=(np.shape(base)[0]))
    print(id_pick)
    boot1=base[id_pick,:]
    tmp[:,:,i]=boot1
print(tmp)

Tags: 代码numpyidforbasenp数组tmp
2条回答

您可以使用numpy中的stack函数。那么你的代码应该是:

base=np.array([[20,30],[50,60],[70,80],[10,30]])
print(np.shape(base))
nsample=10
tmp = []
for i in range(nsample):
    id_pick = np.random.choice(np.shape(base)[0], size=(np.shape(base)[0]))
    print(id_pick)
    boot1=base[id_pick,:]
    tmp.append(boot1)
tmp = np.stack(tmp, axis=-1)
print(tmp)

这里有一个矢量化方法-

m,n = base.shape
idx = np.random.randint(0,m,(m,nsample))
out = base[idx].swapaxes(1,2)

基本思想是生成所有可能的索引,其中np.random.randintidx。这将是一个形状(m,nsample)的数组。我们使用这个数组沿着第一个轴索引输入数组。因此,它从base中选择随机行。为了得到带有形状(m,n,nsample)的最终输出,我们需要交换最后两个轴。在

相关问题 更多 >