python numpy库等差不均分_python – numpy中数组的不均匀段

给定ndarray x和包含x维度的连续切片长度的一维数组,我想计算一个包含所有切片之和的新数组.例如,在二维上总结一维:

>>> lens = np.array([1, 3, 2])

array([1, 3, 2])

>>> x = np.arange(4 * lens.sum()).reshape((4, lens.sum())).astype(float)

array([[ 0., 1., 2., 3., 4., 5.],

[ 6., 7., 8., 9., 10., 11.],

[ 12., 13., 14., 15., 16., 17.],

[ 18., 19., 20., 21., 22., 23.]])

# I want to compute:

>>> result

array([[ 0., 6., 9.],

[ 6., 24., 21.],

[ 12., 42., 33.],

[ 18., 60., 45.]])

# 0 = 0

# 6 = 1 + 2 + 3

# ...

# 45 = 22 + 23

想到的两种方式是:

a)使用cumsum和fancy索引:

def cumsum_method(x, lens):

xc = x.cumsum(1)

lc = lens.cumsum() - 1

res = xc[:, lc]

res[:, 1:] -= xc[:, lc[:-1]]

return res

b)使用bincount并智能地生成适当的bin:

def bincount_method(x, lens):

bins = np.arange(lens.size).repeat(lens) + \

np.arange(x.shape[0])[:, None] * lens.size

return np.bincount(bins.flat, weights=x.flat).reshape((-1, lens.size))

在大输入上对这两个进行定时使得cumsum方法表现稍好一些:

>>> lens = np.random.randint(1, 100, 100)

>>> x = np.random.random((100000, lens.sum()))

>>> %timeit cumsum_method(x, lens)

1 loops, best of 3: 3 s per loop

>>> %timeit bincount_method(x, lens)

1 loops, best of 3: 3.9 s per loop

我错过了一种明显更有效的方式吗?看起来本机c调用会更快,因为它不需要分配cumsum或bin数组.一个接近这个的numpy内置函数可能比(a)或(b)更好.我通过搜索和浏览文档找不到任何东西.

注意,这类似于this question,但总和间隔不规则.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值