推荐学习书目
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 · Dec 1, 2018 · 3195 views
    This topic created in 2718 days ago, the information mentioned may be changed or developed.
    结构化数组可以转换为 record 数组,这是容易查到的,但是我在 google 上查不到 record 向 structrured 转化,难道全世界没有这种需求?
    事情是这样的,我有一个 fits 格式的科学数据表格(非客户个人隐私数据),一百多万行几十列,字符和数字都有。我通过 pyfits 读取后成为 record 数组,想向其中增加几列数据,好像只有结构化数组可以这样操作。大家有什么解决办法么?

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

    谢谢!
    Supplement 1  ·  Dec 2, 2018

    目前的解决方案是:

    #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 replies    2018-12-01 20:20:46 +08:00
    ruoyu0088
        1
    ruoyu0088  
       Dec 1, 2018   ❤️ 1
    文档里面有:

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

    但是添加列应该需要复制所有数据。
    ghhardy
        2
    ghhardy  
    OP
       Dec 1, 2018
    @ruoyu0088 非常感谢!是的,numpy.lib.recfunctions 就是通过复制数组实现的 structrued 增加列
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1267 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:39 · PVG 07:39 · LAX 16:39 · JFK 19:39
    ♥ Do have faith in what you're doing.