gpt4 book ai didi

python - 将 NumPy 数组列表写入 csv

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:42 26 4
gpt4 key购买 nike

我有一个 getX(),它给出一个二维数组 (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)

最佳答案

您可以使用 itertools.chain.from_iterable 取消嵌套 data 并使用 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"

关于python - 将 NumPy 数组列表写入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com