简体   繁体   English

将numpy数组保存到一行中的文件?

[英]Saving numpy array to file in a single line?

On the code bellow I want to save an array to a file in a single line using "numpy.savetxt" but I'm really not sure if I can get this result. 在下面的代码中,我想使用“ numpy.savetxt”将数组保存到一行中的文件中,但是我真的不确定是否可以得到此结果。

import numpy as np

if __name__ == '__main__':
    array = np.array([[ 6, -2.86751284, -0.35808319,  1.79360812],
        [ 6., -1.59351284, -0.02808319, -0.47039188],
        [ 6., 0.51848716,  0.21791681,  0.17060812],
        [ 6., 1.63251284, -0.12208319,  0.90460812],
        [ 6., -0.26051284,  0.03991681,  1.33660812],
        [ 6., 1.87948716,  0.43391681,  0.21960812],
        [ 6., 2.52048716,  0.45191681,  1.44760812],
        [ 6., 0.40448716,  0.04591681,  2.58360812],
        [ 6., 1.81248716,  0.30391681,  2.62260812]], np.float32)

    np.savetxt("img/file.txt", array, fmt="%.3d")

I wanted a result like "006, -002, -003, 001, 006, -001..." with all columns and lines in a single line in the file but separated by commas. 我想要一个结果,如“ 006,-002,-003、001、006,-001 ...”,所有列和行都在文件的一行中,但用逗号分隔。 Can I do it with "numpy.savetxt" or do I have to loop through array to get this result? 我可以使用“ numpy.savetxt”执行此操作,还是必须遍历数组才能获得此结果?

Thank you. 谢谢。

This should produce, what you want: 这应该产生您想要的:

np.savetxt("file.txt", array.flatten(), fmt="%.3d", newline = ", ")

cat file.txt
006, -002, 000, 001, 006, -001, 000, 000, 006, 000, 000, 000, 006, 001, 
000, 000, 006, 000, 000, 001, 006, 001, 000, 000, 006, 002, 000, 001, 
006, 000, 000, 002, 006, 001, 000, 002,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM