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.
>>> 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,)
CodePudding user response:
It can be achieved without using np.tile
:
x[:, 0] = np.array([*np.arange(4)] * 3)
Which will be faster than np.tile
on such small arrays. numba usage will be the fastest for small and large arrays:
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
CodePudding user response:
it came to me moments after I posted. Just use a range of length 1 for the second index into x. Tried, worked.
x[:,0:1] = np.tile(np.reshape(range(4),(4,1)),(3,1))