将对象数组写入.txt文件 [英] Write object array to .txt file

查看:130
本文介绍了将对象数组写入.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做

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(对象")和格式说明符之间出现错误匹配项

I get an error Mismatch between array dtype ('object') and format specifier

任何有关如何克服此问题的帮助? (也许附加到大小不相等的数组上?)

Any help on how I can overcome this issue? (And maybe append to arrays of non equal sizes?)

推荐答案

更多错误消息:

-> 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.

savetxt is iterating over the rows of rsf, and for each trying to create a string that it can write to the file. Without fmt specification from you it tries a default format repeated by the number of columns. That's the format specifier.

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

This is a basic Python string formatting issue.

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:

so you need to call savetxt with something like:

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'简化格式

or you could simplify the format with the generic '%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

这篇关于将对象数组写入.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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