给定边界值k
,是否有一种矢量化的方法将每个数n
替换为从n-1
到k
的连续降序数?例如,如果k
为0,我想用np.array([2,1,0,3,2,1,0,1,0,1,0,0,2,1,0,0])
替换np.array([3,4,2,2,1,3,1])
。输入数组的每一项都大于k
我尝试了np.repeat
和np.cumsum
的组合,但它似乎是回避的解决方案:
x = np.array([3,4,2,2,1,3,1])
y = np.repeat(x, x)
t = -np.ones(y.shape[0])
t[np.r_[0, np.cumsum(x)[:-1]]] = x-1
np.cumsum(t)
还有别的办法吗?我期望np.add.reduceat
的类似smth的逆函数能够将整数广播到递减序列,而不是最小化它们
这是简明扼要的,也许可以提高效率;我不认为
apply
在这里是矢量化的,因此您将主要受到原始数组中元素数量的限制(我猜它们的值较小):下面是另一种通过数组赋值跳过重复部分的方法-
基准测试
使用^{} 包(打包在一起的一些基准测试工具;免责声明:我是它的作者)对建议的解决方案进行基准测试
扩展以
k
作为arg样本运行-
相关问题 更多 >
编程相关推荐