【发布时间】:2018-11-04 04:45:25
【问题描述】:
这个问题之前已经解决过(here、here 和 here)。我想在 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 输出一起工作?
我真的宁愿使用标准的方法来处理这个问题,而不是自制的..
【问题讨论】: