将NumPy数组列表写入CSV

时间:2018-11-06 09:12:33

标签: python arrays csv numpy

我有一个getX(),它为图像的每一帧提供2D数组(shape =(18,2))作为输出。我想将此不断更新的数组添加到csv。我使用了以下代码。但这只会给我一行(可能只有一帧)。

[array([178.,  76.]), array([184.,  92.]), array([164.,  90.]), array([154., 116.]), array([160., 126.]), array([204.,  94.]), array([208., 124.]), array([190., 132.]), array([164., 152.])]

我已经尝试过了:

with open("data.csv",mode ='w') as csvfile:
        wr = csv.writer(csvfile, quoting = csv.QUOTE_ALL,dialect="excel")
        get_val = oneObject.getX(currentFrameIndex)
        for  humanPos in get_val:
            wr.writerow(humanPos)

3 个答案:

答案 0 :(得分:2)

您可以将numpy数组直接保存到csv,不需要任何其他模块。

import numpy as np
array = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("output.csv", array, delimiter=",")

要将其保存为单行并引用输出,可以使用ravel,如建议的@jpp。

import numpy as np
array = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
np.savetxt('output.csv', np.array(array).ravel()[None], fmt='"%s"', delimiter=',')

答案 1 :(得分:2)

您可以将dataitertools.chain.from_iterable嵌套使用,并使用wr.writerow

>>> from itertools import chain
>>> 
>>> with open("data.csv", mode='w') as csvfile:
...:      wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, dialect="excel")
...:      wr.writerow(chain.from_iterable(data))                                                                                                                 

输出:

$ cat data.csv
"178.0","76.0","184.0","92.0","164.0","90.0","154.0","116.0","160.0","126.0","204.0","94.0","208.0","124.0","190.0","132.0","164.0","152.0"

答案 2 :(得分:1)

将数组列表(data)转换为单个数组后,可以使用np.ndarray.ravel。然后根据您所需的精确输出使用csv模块或NumPy。

csv

with open('data.csv', mode='w') as csvfile:
    wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, dialect='excel')
    wr.writerow(np.array(data).ravel())

输出:

"178.0","76.0","184.0","92.0","164.0","90.0","154.0","116.0","160.0","126.0","204.0","94.0","208.0","124.0","190.0","132.0","164.0","152.0"

numpy

要保存一行,您需要通过[None]进行切片。另外,您可以通过np.savetxtfmt参数指定格式。如果您需要基于文本的存储,则最好使用此解决方案来通过NumPy保存和读取数组。

np.savetxt('data.csv', np.array(data).ravel()[None], fmt='%d', delimiter=',')

输出:

178,76,184,92,164,90,154,116,160,126,204,94,208,124,190,132,164,152