将numpy数组转换为带分隔符的字符串并保存到txt文件

时间:2013-11-22 08:48:22

标签: python string numpy

我正在尝试将numpy数组转换为带分隔符的字符串并将其保存到txt文件。

我试过了:

im = np.reshape(gray, (1,n_row*n_col))
res_str= " ".join(map(str, im))

当我在控制台中测试它似乎工作正常,但是当我将它保存到文件时,它变成带有省略号的字符串,如

  

[[48 49 45 ...,47 46 46]]

代码:

with open('file.txt', "a") as myfile:
        myfile.write(np.array_str(im)) #don't work
    #res_str= " ".join(map(str, im))
    #myfile.write(str(res_str))      #also don't work

2 个答案:

答案 0 :(得分:3)

试试这个:

import numpy as np

data = np.random.randint(0,100,size=(1,100))
np.savetxt('data.csv',data,delimiter=',',fmt='%d')     #numpy savetxt

和输出:

[data.csv]

70,53,95,60,91,...

您还可以定义其他格式:

fmt='"%d"'

会导致:

"70","53","95","60","91",...

您可以在 {here}找到有关numpy.savetxt的更多信息。

答案 1 :(得分:0)

将(多维)数组转换为字符串的简单方法是使用tolist()

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> result = str(a.tolist())
>>> result
'[[1, 2], [3, 4]]'

这个result可以保存为各种文件类型。如果你想从这个result字符串恢复numpy数组。您可以使用ast.literal_eval()

>>> import ast
>>> restored_a = np.array(ast.literal_eval('[[1, 2], [3, 4]]'))
>>> restored_a
array([[1, 2],
       [3, 4]])
相关问题