python - 沿 numpy 数组中的范围应用函数

标签 python numpy

假设我有以下 numpy 数组:

a = np.arange(20)

还有一个包含索引的数组,如下所示:

ix = np.array([4,10,15])

我一直在尝试为以下问题提出一个矢量化解决方案:如何使用 ix 中的索引沿着 a 拆分函数?

所以说我在哪里用np.split分割a(我在这里仅使用np.split来说明分组我想在这里应用一个函数):

np.split(a,ix)

[array([0, 1, 2, 3]),
 array([4, 5, 6, 7, 8, 9]),
 array([10, 11, 12, 13, 14]),
 array([15, 16, 17, 18, 19])]

例如,我想对每个 block 求和,因此给出:

[6, 39, 60, 85]

我如何使用numpy对其进行矢量化?

最佳答案

我不知道这是否是最好的解决方案,但是您可以通过添加零将不同大小的数组列表转换为固定大小的数组列表。然后实现一个像 sum 这样不受零影响的函数。

请参阅下面的示例。

a = np.arange(20)
ix = np.array([4,10,15])
b = np.split(a,ix)
print(b)

结果

[array([0, 1, 2, 3]),
 array([4, 5, 6, 7, 8, 9]),
 array([10, 11, 12, 13, 14]),
 array([15, 16, 17, 18, 19])]

然后使用itertools将列表转换为数组from here

import itertools
c = np.array(list(itertools.zip_longest(*b, fillvalue=0))).T
print(c)

结果

[[ 0  1  2  3  0  0]
 [ 4  5  6  7  8  9]
 [10 11 12 13 14  0]
 [15 16 17 18 19  0]]

然后使用

求和
np.sum(c, axis = 1)

结果

array([ 6, 39, 60, 85])

关于python - 沿 numpy 数组中的范围应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54540649/

相关文章:

arrays - python numpy的where和 bool 数组之间的区别

python - 快速降低python中自相关函数噪声的方法?

python - 拥有许多不同的数据类型有什么好处?

python - 按特定值过滤字典

python - 从图片中找到正方形中心

python - numpy:有效地添加矩阵的行

python - 如何从 Linux 上运行的进程的命令行发出命令

python - 从每个组中删除第一行和最后一行

python - 数巴 0.35.0 : Use NumPy out parameter

python - numpy.getbuffer 导致 AttributeError : 'module' object has no attribute 'getbuffer'