【问题标题】:How to write a numpy ndarray to a textfile?如何将 numpy ndarray 写入文本文件?
【发布时间】:2018-10-28 23:35:18
【问题描述】:

假设我使用 numpy 得到了这个 ndarray,我想写入一个文本文件。 :

[[1   2   3   4]
[5   6   7   8]
[9   10   11   12]]

这是我的代码:

width, height = matrix.shape
with open('file.txt', 'w') as foo:
    for x in range(0, width):
        for y in range(0, height):
            foo.write(str(matrix[x, y]))
foo.close()

问题是我在一行中得到了 ndarray 的所有行,但是我希望它像这样写入文件:

1 2 3 4
5 6 7 8
9 10 11 12

【问题讨论】:

    标签: python-3.x text-files numpy-ndarray


    【解决方案1】:

    您可以简单地遍历每一行:

    with open(file_path, 'w') as f:
        for row in ndarray:
            f.write(str(row))
            f.write('\n')
    

    【讨论】:

    • 谢谢,经过一些修改,您的答案就是我要找的答案。我会认为这是正确的答案。
    • @singrium 很高兴为您提供帮助。你做了哪些修改?我可以将它们包含在我的答案中吗?
    【解决方案2】:

    如果您需要保留描述的形状,我会使用pandas 库。 This post 描述了如何做到这一点。

    import pandas as pd
    import numpy as np
    
    your_data = np.array([np.arange(5), np.arange(5), np.arange(5)])
    
    # can pass your own column names if needed
    your_df = pd.DataFrame(your_data) 
    
    your_df.to_csv('output.csv')
    

    【讨论】:

    • 感谢您的回答,您的解决方案完美运行,但我不想使用 pandas。
    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2019-05-18
    • 2014-08-30
    • 2017-07-13
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多