V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-02-18 14:41:56 +08:00 · 2897 次点击
    这是一个创建于 2617 天前的主题,其中的信息可能已经有所发展或是发生改变。

    可能标题说的不太明白

    代码从文件读取数据,然后转为 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 条回复    2017-02-18 15:35:46 +08:00
    ipwx
        1
    ipwx  
       2017-02-18 15:07:10 +08:00   ❤️ 1
    我觉得你这已经是最好的方法了……

    如果你事先知道 maxlen 的话,你可以用 numpy.pad 处理每一条记录。
    nyanyh
        2
    nyanyh  
    OP
       2017-02-18 15:35:46 +08:00
    r#1 @ipwx 就是不知道 max_len 才比较纠结,暂时这么处理了,也没有什么性能要求
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   895 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:19 · PVG 05:19 · LAX 14:19 · JFK 17:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.