V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
going2think
V2EX  ›  Python

numpy 如何取消循环操作

  •  
  •   going2think · Jun 6, 2019 · 2961 views
    This topic created in 2523 days ago, the information mentioned may be changed or developed.

    有如下代码,请问该如何去掉两重 for 循环,使用 numpy 的数组操作来实现呢?谢谢各位了

    import numpy as np
    
    a = np.zeros((100, 100))
    b = np.zeros((100, 100))
    ds = []
    for i in range(5, 95):
        for j in range(5, 95):
            pa = a[i-5:i+5, j-5:j+5]
            pb = b[i-5:i+5, j-5:j+5]
            d = pa - pb
            ds.append(d)
    
    return ds
    
    5 replies    2019-06-07 20:35:48 +08:00
    necomancer
        1
    necomancer  
       Jun 6, 2019   ❤️ 1
    from skimage.util.shape import view_as_windows

    a = np.random.random((100,100))
    b = np.random.random((100,100))

    ret = view_as_windows(a-b, (10,10))

    In [1]: np.allclose(ret[:-1,:-1,:], ds.reshape(90,90,10,10))
    Out[1]: True

    顺带一提,view_as_windows 有 step 函数,你这个情况 step=1,是默认参数。
    necomancer
        2
    necomancer  
       Jun 6, 2019   ❤️ 1
    step=10 在你的例子里应该相当于刚好无重叠,可以用 view_as_blocks 函数。
    necomancer
        3
    necomancer  
       Jun 6, 2019   ❤️ 1
    这个函数基本上是在用 np.lib.stride_tricks.as_strided,所以如果你没有 skimage,去 skimage 找到那个函数拷过来就行。麻烦的地方只在怎么根据 window_size 和 step 算 stride
    going2think
        4
    going2think  
    OP
       Jun 6, 2019
    @necomancer 感谢帮助,我去试试~
    xgdgsc
        5
    xgdgsc  
       Jun 7, 2019
    这种直接改 numba
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   805 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 19:44 · PVG 03:44 · LAX 12:44 · JFK 15:44
    ♥ Do have faith in what you're doing.