[英]Error trying to use np.tile to insert repeated 1d array into column of another array
我需要用一个重复的列表从上到下填充一个数组列。 下面显示了一个玩具示例,其中包含我尝试过的各种方法。
“重塑”方法是我认为可行的方法,但我得到“无法将输入数组从形状(12,1)广播到形状(12,)”错误。
>>> x = np.zeros((12,4))
>>> #x[:,0] = np.tile(range(4),(3,1))
>>> #x[:,0] = np.tile(np.array(range(4)),(3,1))
>>> x[:,0] = np.tile(np.reshape(range(4),(4,1)),(3,1))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [121], in <cell line: 4>()
1 x = np.zeros((12,4))
2 #x[:,0] = np.tile(range(4),(3,1))
3 #x[:,0] = np.tile(range(4),(3,1))
----> 4 x[:,0] = np.tile(np.reshape(range(4),(4,1)),(3,1))
ValueError: could not broadcast input array from shape (12,1) into shape (12,)
它可以在不使用np.tile
情况下实现:
x[:, 0] = np.array([*np.arange(4)] * 3)
在这样的小阵列上,这将比np.tile
更快。 对于小型和大型阵列,numba 的使用将是最快的:
import numba as nb
@nb.njit
def numba_(x):
rows_count = x.shape[0]
range_ = np.arange(x.shape[1])
for i in range(rows_count):
x[i, 0] = range_[i % x.shape[1]]
return x
它在我发布后不久就出现了。 只需使用长度为 1 的范围作为 x 的第二个索引。 试过了,奏效了。
x[:,0:1] = np.tile(np.reshape(range(4),(4,1)),(3,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.