Py学习  »  Python

在Python中以CSV格式保存数组元素

user18796731 • 4 年前 • 1669 次点击  

我想保存 I 以CSV格式。电流和所需输出均已连接。

import numpy as np
import csv

I=np.array([[0, 1],
       [0, 3],
       [1, 2],
       [1, 4],
       [2, 5],
       [3, 4],
       [3, 6],
       [4, 5],
       [4, 7],
       [5, 8],
       [6, 7],
       [7, 8]])

with open('Test123.csv', 'w') as f:
    writer = csv.writer(f)

    # write the data
    writer.writerows(I.T)

电流输出为

enter image description here

所需的输出是

enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133527
文章 [ 1 ]  |  最新文章 4 年前
Epsi95
Reply   •   1 楼
Epsi95    4 年前

你可以尝试使用 writerow 并创建逗号分隔符

import numpy as np
import csv

I=np.array([[0, 1],
       [0, 3],
       [1, 2],
       [1, 4],
       [2, 5],
       [3, 4],
       [3, 6],
       [4, 5],
       [4, 7],
       [5, 8],
       [6, 7],
       [7, 8]])

with open('Test123.csv', 'w') as f:
    writer = csv.writer(f)

    # write the data
    writer.writerow(map(lambda x: f'{x[0]}, {x[1]}', zip(*I.T)))