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
ghhardy
V2EX  ›  Python

如何将 numpy 的 record 数组转换成 structured 数组?

  •  
  •   ghhardy · 2018-12-01 19:58:21 +08:00 · 2203 次点击
    这是一个创建于 1944 天前的主题,其中的信息可能已经有所发展或是发生改变。
    结构化数组可以转换为 record 数组,这是容易查到的,但是我在 google 上查不到 record 向 structrured 转化,难道全世界没有这种需求?
    事情是这样的,我有一个 fits 格式的科学数据表格(非客户个人隐私数据),一百多万行几十列,字符和数字都有。我通过 pyfits 读取后成为 record 数组,想向其中增加几列数据,好像只有结构化数组可以这样操作。大家有什么解决办法么?

    暂不考虑 pandas 和 tables,我主要是关心数组格式之间的转换和 record 有没有增加列数据的办法。

    谢谢!
    第 1 条附言  ·  2018-12-02 13:32:02 +08:00

    目前的解决方案是:

    #record 数组转 structured数组:

    structured_arr = record_arr.view(record_arr.dtype.fields, np.ndarray)
    

    #增加列:

    import numpy.lib.recfunctions as rft
    
    colarr1 = np.array([...])
    colarr2 = np.array([...])
    
    array2 = rft.append_fields(structured_array, names=['colname1', 'colname2'], data=[colarr1, colarr2])
    
    2 条回复    2018-12-01 20:20:46 +08:00
    ruoyu0088
        1
    ruoyu0088  
       2018-12-01 20:13:19 +08:00   ❤️ 1
    文档里面有:

    arr2 = recordarr.view(recordarr.dtype.fields or recordarr.dtype, np.ndarray)

    但是添加列应该需要复制所有数据。
    ghhardy
        2
    ghhardy  
    OP
       2018-12-01 20:20:46 +08:00
    @ruoyu0088 非常感谢!是的,numpy.lib.recfunctions 就是通过复制数组实现的 structrued 增加列
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1904 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:25 · PVG 00:25 · LAX 09:25 · JFK 12:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.