【问题标题】:Write a 2D array to a CSV file in python在 python 中将二维数组写入 CSV 文件
【发布时间】:2021-09-05 20:05:16
【问题描述】:

我有一个来自函数 f.example 的二维数组,它返回给我:

array([[ 0.0, 1.0, 2.0, 3.0 ],
       [ 5.0, 1.0, 3.0, 3.0 ],
       [ 1.0, 1.0, 3.0, 3.0 ]])

事实上,我可以将它写入 csv 文件,但不是我想要的方式。以下是 csv 文件的外观:

0.0 5.0 1.0
1.0 1.0 1.0
2.0 3.0 3.0
3.0 3.0 3.0

但这就是现在的样子:

0.0 1.0 2.0 3.0
5.0 1.0 3.0 3.0
1.0 1.0 3.0 3.0

还有我拥有的代码:

with open('example.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(f.example)

【问题讨论】:

  • 在写出之前转置矩阵

标签: python arrays python-3.x csv


【解决方案1】:

你需要先转置你的数组

import numpy as np
arr = np.array([[0.0, 1.0, 2.0, 3.0],[5.0, 1.0, 3.0, 3.0],[1.0, 1.0, 3.0, 3.0 ]])
arr_t = arr.T
print(arr_t)

输出

[[0. 5. 1.]
 [1. 1. 1.]
 [2. 3. 3.]
 [3. 3. 3.]]

然后如前所述。

【讨论】:

    【解决方案2】:

    如果你不能使用numpy

    代码:

    import csv
    x = [[ 0.0, 1.0, 2.0, 3.0 ],
        [ 5.0, 1.0, 3.0, 3.0 ],
        [ 1.0, 1.0, 3.0, 3.0 ]]
    with open('example.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(list(zip(*x)))
    

    结果:

    0.0,5.0,1.0
    
    1.0,1.0,1.0
    
    2.0,3.0,3.0
    
    3.0,3.0,3.0
    

    【讨论】:

    • 谢谢@leaf_yakitori,两个答案都有帮助!
    猜你喜欢
    • 2018-03-08
    • 2021-01-09
    • 2014-09-13
    • 1970-01-01
    • 2012-09-11
    • 2019-01-29
    • 2011-08-12
    • 2016-09-27
    • 2011-06-06
    相关资源
    最近更新 更多