使用索引列表和应用函数对numpy数组进行切片,是否可以对其进行矢量化(或者采用非向量化的方式)?向量化将是大矩阵的理想选择。
import numpy as np
index = [[1,3], [2,4,5]]
a = np.array(
[[ 3, 4, 6, 3],
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[1, 1, 4, 5]])在index中按行索引组进行求和,给出:
np.array([[8, 10, 12, 14],
[17, 19, 24, 37]])发布于 2017-10-02 21:20:40
方法#1 :,这是一个几乎*矢量化的方法-
def sumrowsby_index(a, index):
index_arr = np.concatenate(index)
lens = np.array([len(i) for i in index])
cut_idx = np.concatenate(([0], lens[:-1].cumsum() ))
return np.add.reduceat(a[index_arr], cut_idx)*几乎是因为用循环理解计算lens的步骤,但是由于我们只是得到长度而不涉及计算,所以这一步骤不会对时间有任何大的影响。
样本运行-
In [716]: a
Out[716]:
array([[ 3, 4, 6, 3],
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[ 1, 1, 4, 5]])
In [717]: index
Out[717]: [[1, 3], [2, 4, 5]]
In [718]: sumrowsby_index(a, index)
Out[718]:
array([[ 8, 10, 12, 14],
[17, 19, 24, 27]])方法2 :我们可以利用numpy.dot的快速矩阵乘法来执行和缩减,给出另一种方法,如下所示-
def sumrowsby_index_v2(a, index):
lens = np.array([len(i) for i in index])
id_ar = np.zeros((len(lens), a.shape[0]))
c = np.concatenate(index)
r = np.repeat(np.arange(len(index)), lens)
id_ar[r,c] = 1
return id_ar.dot(a)发布于 2017-10-02 21:12:56
用list comprehension..。
对于index中的每个index,创建一个新的列表,它是这些indexes的a中的rows的list。从这里,我们有一个list of numpy arrays,我们可以将sum()方法应用到。在numpy array上,sum()将从添加的arrays中返回每个element的新array,这将为您提供您想要的:
np.array([sum([a[r] for r in i]) for i in index])给予:
array([[ 8, 10, 12, 14],
[17, 19, 24, 27]])https://stackoverflow.com/questions/46533746
复制相似问题