python构建矩阵_python-向量化numpy索引并应用函数来构建矩阵

这是一种方法-

# Get a flattened version of indices

idx0 = np.concatenate(I)

# Get indices at which we need to do "intervaled-summation" along axis=1

cut_idx = np.append(0,map(len,I))[:-1].cumsum()

# Finally index into cols of array with flattend indices & perform summation

out = np.add.reduceat(X[:,idx0], cut_idx,axis=1)

分步运行-

In [67]: X

Out[67]:

array([[ 1, 2, 3, 4],

[15, 6, 17, 8]])

In [68]: I

Out[68]: array([[0, 2, 3, 1], [2, 3, 1], [2, 3]], dtype=object)

In [69]: idx0 = np.concatenate(I)

In [70]: idx0 # Flattened indices

Out[70]: array([0, 2, 3, 1, 2, 3, 1, 2, 3])

In [71]: cut_idx = np.append(0,map(len,I))[:-1].cumsum()

In [72]: cut_idx # We need to do addition in intervals limited by these indices

Out[72]: array([0, 4, 7])

In [74]: X[:,idx0] # Select all of the indexed columns

Out[74]:

array([[ 1, 3, 4, 2, 3, 4, 2, 3, 4],

[15, 17, 8, 6, 17, 8, 6, 17, 8]])

In [75]: np.add.reduceat(X[:,idx0], cut_idx,axis=1)

Out[75]:

array([[10, 9, 7],

[46, 31, 25]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值