我有一个numpy数组,维数为1000*30*150。我正在尝试将它保存为txt文件。到目前为止我已经试过了
np.savetxt("test.txt", mydata, fmt='%.5f', delimiter=",")
#and
with open('test.txt', 'w') as f:
for row in mydata:
np.savetxt(f, row, delimiter=',', fmt='%.5f')
这两种方法都给了我错误。
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1254, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: only length-1 arrays can be converted to Python scalars
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
np.savetxt("test.txt", train, fmt='%.5f', delimiter=",")
File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1258, in savetxt
% (str(X.dtype), format))
TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f')
发布于 2017-08-09 02:06:26
您没有提到将三维数组写入文本文件的目的是什么,您将来会读取它吗?您正在寻找什么格式,但这是一种可能性:
import json
print(json.dumps(mydata, default=lambda x: list(x), indent=4))
如果你澄清目的,人们将能够提出更合适的解决方案。
发布于 2017-08-09 01:56:56
问题是你的数组是三维的,不能以二维格式保存。要么重塑它,使它成为2d:
mydata = mydata.reshape(mydata.shape[0],mydata.shape[1]*mydata.shape[2])
np.savetxt('text.txt',mydata,fmt='%.5f',delimiter=',')
或者,如果您不需要将它作为文本文件读取,并且希望稍后在python中重新加载它,请使用:
np.save('text.npy',mydata)
发布于 2017-08-09 01:58:23
告诉我们关于mydata
的事。特别是它的dtype
和shape
。
要用%.5f
格式保存,它需要是一个2d的数字数组。
savetxt
确实这样做了,大致如下:
for row in arr:
print(format % tuple(row))
其中,format
是根据fmt
参数和数组中的数字列构造的。看起来您的数组有大量的列,所以format
是'%.5f,%.5f,%.5f,%.5f,%.5f,%...
字符串。
需要tuple
将该一维数组row
转换为与format%()
一起工作的元组。
如果数组是较高的维度,或者是一个对象数组,那么它就会有问题。
编辑-所以你说数组是1000*30*150。因此,它试图在1000行上迭代,30看起来像那个format
的大小。但它不能将其应用于(30,150)
数组。
对于open
和row
迭代,您会得到相同的错误吗?在'wb'. Iterating yourself on the first dimension means each
savetxtcall works with a 30x150 array. It will iterate on the 30, and try to format rows of 150. The would create a larger
format`,中,您可能需要使用Py3打开,但我认为这会运行。
在任何情况下,savetxt
都是为2d数字数组设计的。3d需要某种软糖。请记住,csv
阅读器也不是为3d数组设计的。它们期望用一个简单的分隔符分隔具有一致列的行。
In [260]: arr = np.arange(24).reshape(4,3,2)
如果允许用%s
格式化每个子行,则可以使用3d。
In [261]: np.savetxt('test',arr, fmt='%s')
In [262]: cat test
[0 1] [2 3] [4 5]
[6 7] [8 9] [10 11]
[12 13] [14 15] [16 17]
[18 19] [20 21] [22 23]
三维数字格式-错误
In [263]: np.savetxt('test',arr, fmt='%d')
....
TypeError: Mismatch between array dtype ('int32') and format specifier ('%d %d %d')
重塑3d到2d -保存作品:
In [264]: np.savetxt('test',arr.reshape(-1,2), fmt='%d')
In [265]: cat test
0 1
2 3
4 5
6 7
8 9
...
22 23
使用额外的迭代;可以在块之间添加空行。
In [267]: with open('test','wb') as f:
...: for row in arr:
...: np.savetxt(f, row, '%d',delimiter=', ')
...:
In [268]: cat test
0, 1
2, 3
4, 5
6, 7
...
22, 23
https://stackoverflow.com/questions/45580330
复制相似问题