【发布时间】:2020-05-25 22:52:43
【问题描述】:
我想用 numpy 以矢量化的方式使用这个函数:
def example(testing, index):
return np.sum(testing[index], axis = 1)
假设我们创建了我们的测试数组和索引数组:
test = np.arange(0, 20)
indices = np.array([[0, 2], [1, 3], [0, 3], [1, 2], [3, 4]])
它完成了我的预期,为数组中的每个列表将列表中带有索引的元素相加:
Input: example(test, indices)
Output: [2 4 3 3 7]
但是,如果我尝试使用可变长度的索引列表,
indices = np.array([[0, 2, 3], [1, 3], [0, 3], [1, 2], [3, 4]])
Input: example(test, indices)
Output: IndexError: arrays used as indices must be of integer (or boolean) type
如果不遍历 indices 数组,我无法让 numpy 执行此功能。我知道 numpy 在第一种情况下创建了一个二维数组,但不是在第二种情况下,但我不确定为什么它无法对一维数组执行矢量化元素操作。由于这些数组在现实生活中实际上非常大并且用于并行化函数,因此我想像第一个示例一样以 numpy 风格的矢量化方式执行此操作。
【问题讨论】:
-
那不是列表数组,而是多维数组
-
您是否考虑过使用带有 1 或 0 条目的掩码?然后,您可以使用矩阵乘法来计算总和 (
dot)。 -
我正在考虑这个选项,但我不确定如何在不使用 for 循环或类似迭代的情况下从不均匀列表中创建掩码。
标签: python arrays pandas numpy vectorization