之前已经解决过这个问题(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_fields
与genfromtxt
我的单行 csv 文件的输出?
我真的宁愿使用标准方法来处理这个问题,而不是家庭酿造。