一个Python的Numpy Arrays列表到CSV?

时间:2016-09-08 22:17:14

标签: python arrays csv numpy

我有一个存储X,Y,Z坐标的Numpy数组的Python列表 - 像这样:

[array([-0.22424938,  0.16117005, -0.39249256])
array([-0.22424938,  0.16050598, -0.39249256])
array([-0.22424938,  0.1598419 , -0.39249256]) ...,
array([ 0.09214371, -0.26184322, -0.39249256])
array([ 0.09214371, -0.26250729, -0.39249256])
array([ 0.09214371, -0.26317136, -0.39249256])]

我想将它们放入CSV文件中,以便我可以在GIS软件中绘制它们。我是Numpy数组的新手,我一直在使用像numpy.ndarray.tofile()这样的方法来获取错误。

我可以使用

迭代列表
for item in list:
    f.write(str(item))

但它将数据作为二进制数据写入文本文件 我只想让每个XYZ值逗号分隔,每行存储一个XYZ值。 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

使用csv模块及其writerows方法:

import csv

with open('my_data.txt', 'w') as f:
    csvwriter = csv.writer(f)
    csvwriter.writerows(list_of_arrays)

答案 1 :(得分:2)

np.savetxt将写下列表:

In [553]: data=[array([-0.22424938,  0.16117005, -0.39249256]),
     ...: array([-0.22424938,  0.16050598, -0.39249256]),
     ...: array([-0.22424938,  0.1598419 , -0.39249256]),
     ...: array([ 0.09214371, -0.26184322, -0.39249256]),
     ...: array([ 0.09214371, -0.26250729, -0.39249256]),
     ...: array([ 0.09214371, -0.26317136, -0.39249256]),]
In [554]: np.savetxt('test.txt',data, delimiter=', ', fmt='%12.8f')
In [555]: cat test.txt
 -0.22424938,   0.16117005,  -0.39249256
 -0.22424938,   0.16050598,  -0.39249256
 -0.22424938,   0.15984190,  -0.39249256
  0.09214371,  -0.26184322,  -0.39249256
  0.09214371,  -0.26250729,  -0.39249256
  0.09214371,  -0.26317136,  -0.39249256

np.savetxt确实保存了一个数组,但如果需要,可以将列表转换为数组:

In [556]: np.array(data)
Out[556]: 
array([[-0.22424938,  0.16117005, -0.39249256],
       [-0.22424938,  0.16050598, -0.39249256],
       [-0.22424938,  0.1598419 , -0.39249256],
       [ 0.09214371, -0.26184322, -0.39249256],
       [ 0.09214371, -0.26250729, -0.39249256],
       [ 0.09214371, -0.26317136, -0.39249256]])

然后迭代遍历行,并写入

f.write(fmt % tuple(row))

其中fmt是您提供的完整字符串,或者是通过复制我提供的较短fmt构建的字符串。

有效savetxt正在做:

In [558]: fmt='%12.8f, %12.8f, %12.8f'
In [559]: for row in data:
     ...:     print(fmt%tuple(row))
     ...:     
 -0.22424938,   0.16117005,  -0.39249256
 -0.22424938,   0.16050598,  -0.39249256
 -0.22424938,   0.15984190,  -0.39249256
  0.09214371,  -0.26184322,  -0.39249256
  0.09214371,  -0.26250729,  -0.39249256
  0.09214371,  -0.26317136,  -0.39249256