将对象数组写入.txt文件

时间:2016-06-08 21:45:26

标签: python numpy

当我这样做时

k=12

rsf = np.zeros((int(k), 9), dtype='object')

for i in range(0, int(k)):
    rsf[i, 0] = "FREQ"
    for j in range(1, 9):
        rsf[i, j] = sampled[8*i+j-1, 0]

然后尝试按

编写
np.savetxt('test.txt', rsf, delimiter=',')

我得到错误数组dtype(' object')和格式说明符

之间不匹配

有关如何克服此问题的任何帮助? (并且可能附加到不相等大小的数组?)

1 个答案:

答案 0 :(得分:8)

更多错误消息:

-> 1162                                     % (str(X.dtype), format))
   1163         if len(footer) > 0:
   1164             footer = footer.replace('\n', '\n' + comments)

TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e')

savetxt正在遍历rsf行,并且每次尝试创建一个可以写入文件的字符串。如果没有fmt规范,它会尝试按列数重复的默认格式。这是format specifier

这是一个基本的Python字符串格式问题。

In [264]: row=rsf[1,:]

In [265]: row
Out[265]: array(['FREQ', 8, 9, 10, 11, 12, 13, 14, 15], dtype=object)

In [266]: '%s, %d, %d, %d, %d, %d, %d, %d, %d'%tuple(row)
Out[266]: 'FREQ, 8, 9, 10, 11, 12, 13, 14, 15'

因此您需要使用以下内容调用savetxt

In [267]: fmt='%s, %d, %d, %d, %d, %d, %d, %d, %d'

In [268]: np.savetxt('test.txt',rsf,fmt=fmt)

In [269]: cat test.txt
FREQ, 0, 1, 2, 3, 4, 5, 6, 7
FREQ, 8, 9, 10, 11, 12, 13, 14, 15
FREQ, 16, 17, 18, 19, 20, 21, 22, 23
FREQ, 24, 25, 26, 27, 28, 29, 30, 31
...

或者您可以使用通用'%s'

简化格式
In [270]: np.savetxt('test.txt',rsf,fmt='%5s',delimiter=',')

In [271]: cat test.txt
 FREQ,    0,    1,    2,    3,    4,    5,    6,    7
 FREQ,    8,    9,   10,   11,   12,   13,   14,   15
 FREQ,   16,   17,   18,   19,   20,   21,   22,   23
 FREQ,   24,   25,   26,   27,   28,   29,   30,   31
 FREQ,   32,   33,   34,   35,   36,   37,   38,   39