我有一个 sum 函数,在简化版本中,它看起来像这样:用作指标的行数组在我的程序中动态变化,但这是一个大大简化的版本来演示这个问题:
如果我将一些整数放入 Row1 数组中,这将运行得很好,这显然是有意为之的,但是由于在我的程序中存在其中一个行数组为空的实例,我在考虑是否可以制作 numpy执行此任务而不抛出错误。让我们
arr = np.array([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1])
Row1 = np.array([])
Row2 = np.array([1,2])
Col = np.array([0,2])
Result = np.sum(arr[Row1[:, None], Col]) + np.sum(arr[Row2[:, None], Col]
这显然可以解释为返回 4 (0 + 4) 但 numpy 显然会抛出一个错误,因为我正在尝试索引一个 0 维数组。我可以通过这样做来解决这个问题:
arr = np.array([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1])
Row1 = np.array([])
Row2 = np.array([1,2])
Col = np.array([0,2])
sum1 = np.sum(arr[Row1[:, None], Col]) if len(Row1) > 0 else 0
sum2 = np.sum(arr[Row2[:, None], Col]) if len(Row2) > 0 else 0
Result = sum1 + sum2
这会工作得很好,但我的代码中需要数百行感觉有点不必要的额外行,所以我只是想知道是否有人有更有效的方法来解决这个问题。谢谢你!
请您参考如下方法:
"This could obviously be interpreted to return 4 (0 + 4) but numpy will obviously throw an error as I'm trying to indice a 0 dimension array. I could solve this by doing:"
不,只要您确保空数组具有 dtype int,它就可以正常工作。
arr = np.array(([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]))
Row1 = np.array([], dtype=int)
Row2 = np.array([1,2])
Col = np.array([0,2])
Result = np.sum(arr[Row1[:, None], Col]) + np.sum(arr[Row2[:, None], Col])
Result
# 4
