简体   繁体   English

尝试使用 np.tile 将重复的一维数组插入另一个数组的列时出错

[英]Error trying to use np.tile to insert repeated 1d array into column of another array

I need to fill an array column from top to bottom with a list that repeats.我需要用一个重复的列表从上到下填充一个数组列。 A toy example is shown below, with the various approaches I have tried.下面显示了一个玩具示例,其中包含我尝试过的各种方法。

The "reshape" approach was the one I thought would work, but I get the "could not broadcast input array from shape (12,1) into shape (12,)" error. “重塑”方法是我认为可行的方法,但我得到“无法将输入数组从形状(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,)

It can be achieved without using np.tile :它可以在不使用np.tile情况下实现:

x[:, 0] = np.array([*np.arange(4)] * 3)

Which will be faster than np.tile on such small arrays.在这样的小阵列上,这将比np.tile更快。 numba usage will be the fastest for small and large arrays:对于小型和大型阵列,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

it came to me moments after I posted.它在我发布后不久就出现了。 Just use a range of length 1 for the second index into x.只需使用长度为 1 的范围作为 x 的第二个索引。 Tried, worked.试过了,奏效了。

x[:,0:1] = np.tile(np.reshape(range(4),(4,1)),(3,1))

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

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