【发布时间】:2017-02-25 04:52:31
【问题描述】:
给定两个数组,比如说
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)
有没有办法为一组二维数组复制此功能?
这是给定的
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,而且我知道它不会比普通版本带来任何性能优势。
【问题讨论】:
标签: python arrays numpy vectorization