Mat*_*ias 5 python numpy writetofile
我需要将3个numpy数组写入txt文件.该文件的头部看起来像这样:
#Filexy
#time operation1 operation2
Run Code Online (Sandbox Code Playgroud)
numpy数组如下所示:
time = np.array([0,60,120,180,...])
operation1 = np.array([12,23,68,26,...)]
operation2 = np.array([100,123,203,301,...)]
Run Code Online (Sandbox Code Playgroud)
最后,.txt文件应该如下所示(分隔符应该是一个选项卡):
#Filexy
#time operation1 operation2
0 12 100
60 23 123
120 68 203
180 26 301
.. ... ...
Run Code Online (Sandbox Code Playgroud)
我尝试了"numpy.savetxt" - 但我没有得到我想要的格式.
非常感谢您的帮助!
我不确定你尝试了什么,但你需要使用header中的参数np.savetxt。此外,您需要正确连接数组。最简单的方法是使用np.c_,它将一维数组强制转换为二维数组,然后按照您期望的方式连接它们。
>>> time = np.array([0,60,120,180])\n>>> operation1 = np.array([12,23,68,26])\n>>> operation2 = np.array([100,123,203,301])\n>>> np.savetxt(\'example.txt\', np.c_[time, operation1, operation2],\n header=\'Filexy\\ntime operation1 operation2\', fmt=\'%d\',\n delimiter=\'\\t\')\nRun Code Online (Sandbox Code Playgroud)\n\nexample.txt现在包含:
# Filexy\n# time operation1 operation2\n0 12 100\n60 23 123\n120 68 203\n180 26 301\nRun Code Online (Sandbox Code Playgroud)\n\n另请注意使用 来fmt=\'%d\'获取输出中的整数值。savetxt默认情况下将保存为浮点数,即使对于整数数组也是如此。
关于分隔符,您只需要使用delimiter参数即可。这里还不清楚,但事实上,列之间有制表符。例如,vim使用点向我显示选项卡:
# Filexy\n# time operation1 operation2\n0\xc2\xb7 12\xc2\xb7 100\n60\xc2\xb7 23\xc2\xb7 123\n120\xc2\xb768\xc2\xb7 203\n180\xc2\xb726\xc2\xb7 301\nRun Code Online (Sandbox Code Playgroud)\n\n附录:
\n\n如果您想添加标头并在数组之前添加额外的行,您最好创建一个自定义标头,并包含您自己的注释字符。使用comment参数来防止savetxt添加额外的#\。
>>> extra_text = \'Answer to life, the universe and everything = 42\'\n>>> header = \'# Filexy\\n# time operation1 operation2\\n\' + extra_text\n>>> np.savetxt(\'example.txt\', np.c_[time, operation1, operation2], \n header=header, fmt=\'%d\', delimiter=\'\\t\', comments=\'\')\nRun Code Online (Sandbox Code Playgroud)\n\n产生
\n\n# Filexy\n# time operation1 operation2\nAnswer to life, the universe and everything = 42\n0 12 100\n60 23 123\n120 68 203\n180 26 301\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2955 次 |
| 最近记录: |