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

Saving array elements in CSV format in Python

我想以 CSV 格式保存 I 的元素。附上当前和所需的输出。

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)

当前输出为

期望的输出是

您可以尝试使用 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)))