推荐学习书目
› 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
nyanyh
V2EX  ›  Python

初学 Python , Numpy 如何将包含不同大小 3d-array 的 list 转为大小相同的 4d-array 呢?

  •  
  •   nyanyh · Feb 18, 2017 · 3423 views
    This topic created in 3505 days ago, the information mentioned may be changed or developed.

    可能标题说的不太明白

    代码从文件读取数据,然后转为 3d array ,之后 append 到一个 list ,但是每个 array 的 shape 不一定相同,这样无法直接转为 numpy.array. 比如有的是(1, 2, 3),但有的就是(1, 2, 5),我想把每个 array 都转成最长的(1, 2, 5),多余部分填 0

    我现在用的代码是:

    max_len = np.max([item.shape[2] for item in old_array])
    new_array = np.zeros((len(old_array), 1, 2, max_len))
    for index, data in enumerate(old_array):
        new_array[index][:, :, :data.shape[2]] = data
    

    有更好的实现方式吗?

    2 replies  •  2017-02-18 15:35:46 +08:00
    ipwx
        1
    ipwx  
       Feb 18, 2017   ❤️ 1
    我觉得你这已经是最好的方法了……

    如果你事先知道 maxlen 的话,你可以用 numpy.pad 处理每一条记录。
    nyanyh
        2
    nyanyh  
    OP
       Feb 18, 2017
    r#1 @ipwx 就是不知道 max_len 才比较纠结,暂时这么处理了,也没有什么性能要求
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2571 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 02:30 · PVG 10:30 · LAX 19:30 · JFK 22:30
    ♥ Do have faith in what you're doing.