如何显式指定np.ufunc.reduceat的最后一个索引 [英] How to specify the last index explicitly to np.ufunc.reduceat

查看:189
本文介绍了如何显式指定np.ufunc.reduceat的最后一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组

data = np.arange(6)

我想使用 np.add.reduceat . 1

如果我这样做:

np.add.reduceat(data, [0, 6, 3])[::2]

我立即收到错误消息

IndexError: index 6 out-of-bounds in add.reduceat [0, 6)

如果我这样做

np.add.reduceat(data, [0, 5, 3])[::2]

我得到了错误的答案(10应该是15):

I get the wrong answer (10 should be 15):

array([10, 12])

我唯一能想到的解决方案是掩盖需要最后一个索引的位置,从中减去1,然后在其中添加最后一个元素:

The only solution I have been able to come up with is to mask the locations where the last index is necessary, subtract 1 from them, and then add the last element back in there:

index = np.array([0, 6, 3])
mask = (index == data.size)
index[mask] -= 1
result = np.add.reduceat(data, index)
# Mask is shifted back by one because it's the previous element that needs to be updated
result[:-1][mask[1:]] += data[-1]

然后result[::2]提供所需的答案.这看起来像是一场巨大的争夺,我希望这是一种优雅的单线(并且比这更快).

Then result[::2] gives the desired answer. This looks like a giant kludge for something that I would expect to be an elegant one-liner (and faster than this).

1 完全意识到有更好的方法可以做到这一点.为了说明的目的,这只是一个人为的例子.这个问题的真正问题源于试图解决 numpy:针对大量线段/点的快速规则间隔平均值.

1 I am fully aware that there are better ways to do this. This is just a contrived example for purposes of illustration. The real problem for this question originated with an attempt to solve numpy: fast regularly-spaced average for large numbers of line segments / points.

推荐答案

我并没有太多使用reduceat,但是看起来您只能拥有一个开放式范围,即一个add to the end.

I haven't used reduceat much, but it looks like you can only have one open ended range, one add to the end.

一种解决方法是填充数组(是的,我通常会反对使用np.append :)):

One way around that is to pad the array (yes, I do normally rail against using np.append :) ):

In [165]: np.add.reduceat(np.append(x,0),[0,6,3])
Out[165]: array([15,  0, 12])

或具有完整范围的配对:

or with a full pairing of ranges:

In [166]: np.add.reduceat(np.append(x,0),[0,6,3,6])
Out[166]: array([15,  0, 12,  0])

我省略了通常的[:: 2]来说明正在发生的事情.

I omitted the usual [::2] to clarify what is going on.

这篇关于如何显式指定np.ufunc.reduceat的最后一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆