【问题标题】:Iterating over a numpy array迭代一个numpy数组
【发布时间】:2011-08-06 14:27:03
【问题描述】:

有没有更简洁的替代方法:

for x in xrange(array.shape[0]):
    for y in xrange(array.shape[1]):
        do_stuff(x, y)

我想出了这个:

for x, y in itertools.product(map(xrange, array.shape)):
    do_stuff(x, y)

这节省了一个缩进,但仍然很丑。

我希望看起来像这样的伪代码:

for x, y in array.indices:
    do_stuff(x, y)

有类似的东西吗?

【问题讨论】:

标签: python numpy


【解决方案1】:

我认为您正在寻找ndenumerate

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

关于性能。它比列表理解要慢一些。

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

如果您担心性能,您可以通过查看ndenumerate 的实现来进一步优化,它做了两件事,转换为数组和循环。如果你知道你有一个数组,你可以调用平面迭代器的.coords 属性。

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

【讨论】:

  • 请注意,这是可行的,但速度非常慢。你最好手动迭代。
【解决方案2】:

如果你只需要索引,你可以试试numpy.ndindex:

>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

【讨论】:

    【解决方案3】:

    nditer

    import numpy as np
    Y = np.array([3,4,5,6])
    for y in np.nditer(Y, op_flags=['readwrite']):
        y += 3
    
    Y == np.array([6, 7, 8, 9])
    

    y = 3 不起作用,请改用 y *= 0y += 3

    【讨论】:

    • 或使用 y[...]=3
    【解决方案4】:

    我发现这里没有使用numpy.nditer() 的好方法。所以,我要带一个。 根据NumPy v1.21 dev0 manual 的说法,NumPy 1.6 中引入的迭代器对象 nditer 提供了许多灵活的方式来系统地访问一个或多个数组的所有元素。

    我必须计算 mean_squared_error 并且我已经计算了 y_predicted 并且我有来自波士顿数据集的 y_actual,可用于 sklearn。

    def cal_mse(y_actual, y_predicted):
        """ this function will return mean squared error
           args:
               y_actual (ndarray): np array containing target variable
               y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
           returns:
               mse (integer)
        """
        sq_error = 0
        for i in np.nditer(np.arange(y_pred.shape[0])):
            sq_error += (y_actual[i] - y_predicted[i])**2
        mse = 1/y_actual.shape[0] * sq_error
        
        return mse
    

    希望这会有所帮助:)。进一步解释visit

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2021-06-02
      • 2021-09-08
      • 1970-01-01
      • 2018-03-13
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多