Numpy.savetxt格式问题:添加字符串列

时间:2018-09-19 12:49:18

标签: python python-3.x numpy string-formatting

我将问题缩小到以下范围:

import numpy as np

out_file = "results.txt"
results = [[1,2,3,.4,"5"]] # just one row for testing
format = ['%i', '%i', '%i', '%f', '%s']

np.savetxt(out_file, results, format, '\t')

我只是想保存5列数据:3个整数,1个浮点数和一个字符串。尝试这样做时,我收到错误消息:

File ".\npyio.py", line 1391, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U32') and format specifier ('%i      %i      %i      %f      %s')

如果我删除字符串格式和数组中的相应值,代码将正常工作。

这种感觉 就像我只是在做一些愚蠢的事情一样,但是经过数小时毫无结果的谷歌搜索后,我认为我需要帮助。

1 个答案:

答案 0 :(得分:1)

普通numpy数组仅具有一种数据类型。您可以使用dtype='O'对象类型初始化该数组,但它对savetxt()无效。

解决问题的方法是here所示的结构化数组。