且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 21:19:40

将数组(和新字段)重塑为大小(1,).仅用一行, genfromtxt 将数据加载为0d数组,形状为(). rfn 代码并未得到广泛使用,并且也不如应有的健壮性.换句话说,标准方式"还是有点小问题.

Reshape the array (and new field) to size (1,). With just one line, the genfromtxt is loading the data as a 0d array, shape (). The rfn code isn't heavily used, and isn't a robust as it should be. In other words, the 'standard way' is still bit buggy.

例如:

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创建一个收件人数组,然后按名称逐个复制字段.

Nothing wrong with the home_brew. Most of the rfn functions use that mechanism - define a new dtype, create a recipient array with that dtype, and copy the fields over, name by name.