这一点以前已经解决过(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中所建议的那样)在使用大小为1的数组时使用len()
失败:
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
输出?我宁愿用一种标准的方法来处理这个问题,也不愿用一种自制的方法。
发布于 2018-11-04 05:04:23
将数组(和新字段)重塑为大小(1,)。只需一行,genfromtxt
就会将数据加载为0d数组-- array ()。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的收件人数组,并按名称复制字段。
https://stackoverflow.com/questions/53137822
复制相似问题