【问题标题】:Multidimensional arrays, using range, while simultaneously having a set start, stop, and step?多维数组,使用范围,同时具有设置的开始、停止和步骤?
【发布时间】:2014-03-12 20:06:55
【问题描述】:

朋友们,

我正在自学 numpy 并且掌握得很好,但即使在阅读了 documentation 之后,我仍然无法理解一些概念。我正在尝试遍历这个矩阵,并让每一行都有 10 秒。

data = np.ones(50).reshape(5,10)
xmax = data.shape[0]
ymax = data.shape[1]
data[range(xmax)::2,range(ymax)] = 10

最后一行代码不正确。我知道如何使用分号进行切片 - list[start:stop:step] 并且我知道如何使用逗号 ndarray[range(end1),range(end2)] 使用精美的索引来遍历矩阵,但是如何结合这两种方法呢?

如何使用范围逐步遍历多维数组,同时设置开始、停止和步进?

【问题讨论】:

    标签: python arrays numpy multidimensional-array


    【解决方案1】:

    我想你想要的是这样的:

    >>> data[range(xmax)[::2],:] = 10
    >>> data
    array([[ 10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.],
           [  1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.],
           [ 10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.],
           [  1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.],
           [ 10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.,  10.]])'
    

    问题就在这里:

     >>> range(xmax)::
           File "<stdin>", line 1
            range(xmax)::
                       ^
        SyntaxError: invalid syntax
    

    您需要将切片语法显式应用于范围:

     >>> range(xmax)[::2]
     [0, 2, 4]
    

    作为一般参考,您可以这样做:

    data[np.arange(start1, end1, step1), np.arange(start2, end2, step2)]
    

    第一个np.arange 选择行,第二个np.aranage 选择列。

    一些可能有帮助的参考资料:

    【讨论】:

    • 太好了,我现在完全明白了。谢谢!不过,这似乎并不能解释这种事情: any_data[range(xmax-1,-1,-1), range(ymax)] = 0
    • @chopperdrawlion4 这只会反转行-您可以像data[::-1]那样做类似且更有效的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2019-06-29
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多