如何将numpy.savetxt与包含数组的结构化数组一起使用 [英] How to use numpy.savetxt with a structured array that contains an array

查看:65
本文介绍了如何将numpy.savetxt与包含数组的结构化数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个结构化数组,如下所示:

Say I have a structured array as follows:

a = np.zeros(10,dtype=[('label1',np.int32, 4), ('label2', np.float_)])

然后我尝试将其另存为csv文件:

And I try to save this as a csv file:

np.savetxt('output.csv', a, fmt='%d,%d,%d,%d,%f')

Python会产生此错误:

Python will generate this error:

ValueError: fmt has wrong number of % formats:  %d,%d,%d,%d,%f

我无法创建适合我的输出的fmt字符串.%s在这里对我不起作用,因为我需要能够指定浮点数的格式.

I haven't been able to create a fmt string that would suit my output. %s won't work for me here as I need the ability specify the format of the float.

是否可以通过这种类型的结构化数组创建csv文件?

Is it possible to create a csv file from this type of structured array?

推荐答案

本质上, savetxt 的作用是:

for row in arr:
    print(fmt % tuple(row))

因此, fmt 必须与 row ,或者在这种情况下,是数组的元素一起使用.

So the fmt has to work with a row, or in this case, an element of your array.

In [330]: a = np.zeros(10,dtype=[('label1',np.int32, 4), ('label2', np.float_)])
     ...: 
In [331]: a
Out[331]: 
array([([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.)], 
      dtype=[('label1', '<i4', (4,)), ('label2', '<f8')])
In [332]: a[0]
Out[332]: ([0, 0, 0, 0],  0.)
In [333]: tuple(a[0])
Out[333]: (array([0, 0, 0, 0]), 0.0)

label1 中嵌套4个int使得很难提出一种有效的格式.这与如何使用Python'%'格式有关.

Nesting the 4 ints in label1 makes it difficult to come up with a format that works. It's a matter of how to Python '%' formatting.

In [334]: '%s, %f'%_
Out[334]: '[0 0 0 0], 0.000000'

如果 a 是5个字段,则会更容易

If a was 5 fields it would be easier

In [335]: a = np.zeros(10,dtype='i,i,i,i,f')
In [336]: a
Out[336]: 
array([(0, 0, 0, 0,  0.),....
       (0, 0, 0, 0,  0.)], 
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<f4')])
In [337]: tuple(a[0])
Out[337]: (0, 0, 0, 0, 0.0)
In [338]: '%d, %d, %d, %d, %f'%tuple(a[0])
Out[338]: '0, 0, 0, 0, 0.000000'

我认为您需要展平"阵列的结构,或编写自定义的 savetxt .正如我指出的那样, savetxt 并不理想.如果您可以按所需格式逐元素 print 数组元素,则可以将该格式写入文件.

I think you need to either 'flatten' the structure of your array, or write a custom savetxt. As I indicated savetxt is not fancy. If you can print the array element by element in the format you want, you can write that format to a file.

这篇关于如何将numpy.savetxt与包含数组的结构化数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆