如何遍历 numpy 数组并执行计算?

How do I iterate through a numpy array and perform calculations?

我想遍历一个 numpy 数组并执行除法、乘法和加法。我一直在想出几个错误。最新的是

IndexError: invalid index to scalar variable.

import numpy as np
rays = np.array([[7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03)],[2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04, 1.791e-03]])

for i in range(rays):
    for w in range(i):
        estimate = rays[0][i]/(rays[0][i]+rays[1][i])

正在修正您的 rays 定义:

rays = [
    [7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03],
    [2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04, 1.791e-03]
]

我们可以像这样迭代计算您的估计值:

for r0, r1 in zip(*rays):
    estimate = r0 / (r0 + r1)
    print(estimate)

如果你对zip不熟悉(注意zip(*rays)zip(rays[0], rays[1])是一样的),以上基本等价于:

for i in range(len(rays[0])):  # assuming all rays have same length!
    r0, r1 = rays[0][i], rays[1][i]
    estimate = r0 / (r0 + r1)
    print(estimate)

zip 版本被认为更“pythonic”(显然更简洁)。

rays = [
[7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03],
[2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04],
]

for i in range(min(len(rays[0]), len(rays[1]))):
    estimate = rays[0][i] / (rays[0][i] + rays[1][i])
    print(estimate)

您的示例存在几个问题(其中一些可能是实际问题,其他只是拼写错误或过度简化):

import numpy as np     # if you want to use for-loops don't use numpy
rays = np.array(...    # closing parentheses instead of brackets
                       # unequal dimensions row of 5 and row of 6
                            
for i in range(rays):  # rays is not a number, did you mean len(rays[0])?
    for w in range(i): # w is not used anywhere
        estimate = rays[0][i]/(rays[0][i]+rays[1][i]) 
                       # estimate is overwritten at each iteration

使用 numpy 的全部意义在于避免使用 for 循环“手动”迭代数组元素。您应该将结果视为矩阵(或向量)之间的运算:

例如(没有for循环):

import numpy as np
rays = np.array([[7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03],
                 [2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04]])

estimates = rays[0]/(rays[0]+rays[1])
print(estimates)
[0.76326816 0.51437045 0.51634316 0.96286712 0.90529456]

请注意,我删除了第二行的最后一个值,因为 numpy 需要固定尺寸(即它不能有一行有 5 个元素而另一行有 6 个)

你的嵌套循环 for w in range(i),虽然你没有对 w 做任何事情,但表明你可能正在寻找累积和之间的比率。如果是这种情况,请使用 numpy 中的 cumsum 函数:

estimates = np.cumsum(rays[0])/np.cumsum(rays[0]+rays[1])
print(estimates)
[0.76326816 0.61753153 0.58805087 0.65726163 0.67565445]