我有一个尺寸为1000 * 30 * 150的numpy数组。我正在尝试将其另存为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')

最佳答案

您没有提到将3-d数组写入文本文件的目的是什么,将来是否会读回它,以及想要什么格式,但这是一种可能:

import json
print(json.dumps(mydata, default=lambda x: list(x), indent=4))

如果您阐明目的,人们将能够提出更合适的解决方案。

关于python - TypeError : Mismatch between array dtype ('float64' ) and format specifier,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45580330/

10-12 19:52