arr = array([10, 24, 24, 24, 1, 21, 1, 21, 0, 0], dtype=int32)
rep = array([3, 2, 2, 0, 0, 0, 0, 0, 0, 0], dtype=int32)
np.repeat(ARR,REP)返回
array([10, 10, 10, 24, 24, 24, 24], dtype=int32)
是否有任何方式来复制此功能的一组2D阵列?
是给予
arr = array([[10, 24, 24, 24, 1, 21, 1, 21, 0, 0],
[10, 24, 24, 1, 21, 1, 21, 32, 0, 0]], dtype=int32)
rep = array([[3, 2, 2, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 2, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)
是否有可能创造出一个矢量化功能?
PS:每行重复次数不必相同。我填充每个结果行以确保它们具有相同的大小。
def repeat2d(arr, rep):
# Find the max length of repetitions in all the rows.
max_len = rep.sum(axis=-1).max()
# Create a common array to hold all results. Since each repeated array will have
# different sizes, some of them are padded with zero.
ret_val = np.empty((arr.shape[0], maxlen))
for i in range(arr.shape[0]):
# Repeated array will not have same num of cols as ret_val.
temp = np.repeat(arr[i], rep[i])
ret_val[i,:temp.size] = temp
return ret_val
我知道np.vectorize,并且我知道它不会给普通版本带来任何性能优势。
每行重复的总数不必相同。这就是为什么我找到maxlen,然后填充每一行的大小相同。 – Aditya369
你正在填充随机'空'值?我见过可以处理可变长度行的蒙版插入,但不记得细节。 – hpaulj
是的。我用随机的空值填充它们。尽管在我的情况下填充零点更有意义。 – Aditya369