向结构化numpy数组添加字段(4)

2024-02-23

之前已经解决过这个问题(here https://stackoverflow.com/questions/21413947/adding-a-field-to-a-structured-numpy-array-3, here https://stackoverflow.com/questions/5288736/adding-a-field-to-a-structured-numpy-array-2 and here https://stackoverflow.com/questions/1201817/adding-a-field-to-a-structured-numpy-array)。我想向 numpy 返回的结构体数组添加一个新字段genfromtxt(还问here https://stackoverflow.com/questions/40182466/is-it-possible-to-add-a-new-field-in-a-numpy-genfromtxt-output).

我的新问题是我正在读取的 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')])

Using 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 https://stackoverflow.com/questions/21413947/adding-a-field-to-a-structured-numpy-array-3) 我发现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 https://stackoverflow.com/questions/25427197/numpy-add-column-to-existing-structured-array。这有效:

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_fieldsgenfromtxt我的单行 csv 文件的输出? 我真的宁愿使用标准方法来处理这个问题,而不是家庭酿造。


将数组(和新字段)重新调整为大小 (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函数使用该机制 - 定义一个新的数据类型,使用该数据类型创建一个接收者数组,然后按名称复制字段。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

向结构化numpy数组添加字段(4) 的相关文章