我是Python初学者。这就是我正在尝试做的事情:
import numpy as np
r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T
r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T
r_comb = np.array([[r10],[r6]]).T
np.savetxt('out.txt',r_comb)
使用 np.savetxt 会出现以下错误,因为它仅支持一维数组:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding)
1433 try:
-> 1434 v = format % tuple(row) + newline
1435 except TypeError:
TypeError: only size-1 arrays can be converted to Python scalars
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-88-c3147f076055> in <module>
----> 1 np.savetxt('out.txt',r_comb)
<__array_function__ internals> in savetxt(*args, **kwargs)
~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding)
1434 v = format % tuple(row) + newline
1435 except TypeError:
-> 1436 raise TypeError("Mismatch between array dtype ('%s') and "
1437 "format specifier ('%s')"
1438 % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e')
是否有其他方法可以将变量 r_comb 的内容保存到 .txt 文件中,以便我可以将其用于其他绘图程序? 基本上,我希望文本文件看起来像这样:
0 0.0 0 0.0
1 0.1 1 0.1
2 0.2 2 0.2
3 0.3 3 0.3
4 0.4 4 0.4
5 0.5 5 0.5
6 0.6
7 0.7
8 0.8
9 0.9
显示文本文件内容外观的图像
最佳答案
黑客但有效
import numpy as np
r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T
r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T
# np array with nans
data = np.empty((np.max([r10.shape[0], r6.shape[0]]),4))
data[:] = np.NaN
for i in range(2):
data[0:len(r10[:,i]), i] = r10[:, i]
for i in range(2):
data[0:len(r6[:,i]), i+2] = r6[:, i]
# replace nans and save
data = data.astype(str)
data[data=='nan'] = ''
np.savetxt("out.txt", data, delimiter=" ", fmt="%s")
out.txt
的内容
0.0 0.0 0.0 0.0
1.0 10.0 1.0 10.0
2.0 20.0 2.0 20.0
3.0 30.0 3.0 30.0
4.0 40.0 4.0 40.0
5.0 50.0 5.0 50.0
6.0 60.0
7.0 70.0
8.0 80.0
9.0 90.0
关于python - 将由不同形状的 numpy 数组组成的 numpy 数组保存到 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62745685/