【问题标题】:Adding a field to a structured numpy array (4)向结构化 numpy 数组添加字段 (4)
【发布时间】:2018-11-04 04:45:25
【问题描述】:

这个问题之前已经解决过(hereherehere)。我想在 numpy genfromtxt 返回的结构数组中添加一个新字段(也询问了here)。

我的新问题是我正在读取的csv文件只有一个标题行和一个数据行:

output-Summary.csv:

Wedge, DWD, Yield (wedge), Efficiency
1, 16.097825, 44283299.473156, 2750887.118836

我正在通过genfromtxt 读取它并计算一个新值'tl'

test_out = np.genfromtxt('output-Summary.csv', delimiter=',', names=True)
tl = 300 / test_out['DWD']

test_out 看起来像这样:

array((1., 16.097825, 44283299.473156, 2750887.118836),
      dtype=[('Wedge', '<f8'), ('DWD', '<f8'), ('Yield_wedge', '<f8'), ('Efficiency', '<f8')])

使用 recfunctions.append_fields(如上面示例 1-3 中所建议的那样)无法将 len() 用于大小为 1 的数组:

from numpy.lib import recfunctions as rfn
rfn.append_fields(test_out,'tl',tl)

TypeError: len() of unsized object

寻找替代品(答案之一here)我发现mlab.rec_append_fields 效果很好(但已弃用):

mlab.rec_append_fields(test_out,'tl',tl)

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: MatplotlibDeprecationWarning: The rec_append_fields function was deprecated in version 2.2.
  """Entry point for launching an IPython kernel.
rec.array((1., 16.097825, 44283299.473156, 2750887.118836, 18.63605798),
          dtype=[('Wedge', '<f8'), ('DWD', '<f8'), ('Yield_wedge', '<f8'), ('Efficiency', '<f8'), ('tl', '<f8')])

我还可以按照here 的建议“手动”将数组复制到新的结构化数组中。这有效:

test_out_new = np.zeros(test_out.shape, dtype=new_dt)
for name in test_out.dtype.names:
    test_out_new[name]=test_out[name]
test_out_new['tl']=tl

总而言之 - 有没有办法让 recfunctions.append_fields 与我的单行 csv 文件的 genfromtxt 输出一起工作? 我真的宁愿使用标准的方法来处理这个问题,而不是自制的..

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    将数组(和新字段)重塑为大小 (1,)。只需一行,genfromtxt 就将数据加载为 0d 数组 shape ()。 rfn 代码没有被大量使用,也不是应有的健壮性。换句话说,“标准方式”仍然有点错误。

    例如:

    In [201]: arr=np.array((1,2,3), dtype='i,i,i')
    In [202]: arr.reshape(1)
    Out[202]: array([(1, 2, 3)], dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])
    
    In [203]: rfn.append_fields(arr.reshape(1), 't1',[1], usemask=False)
    Out[203]: 
    array([(1, 2, 3, 1)],
          dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('t1', '<i8')])
    

    home_brew 没有问题。大多数rfn 函数都使用该机制——定义一个新的dtype,使用该dtype 创建一个接收者数组,然后按名称复制字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      相关资源
      最近更新 更多