[英]A Python list of Numpy Arrays to CSV?
I have a Python list of Numpy arrays storing X, Y, Z coordinates - like this: 我有一个存储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])]
And I would like to get them into a CSV file so I can plot them in GIS software. 而且我想将它们保存为CSV文件,以便可以在GIS软件中进行绘制。 I am new to Numpy arrays and I keep getting errors using methods like numpy.ndarray.tofile().
我是Numpy数组的新手,并且使用numpy.ndarray.tofile()之类的方法不断出错。
I can iterate the list using 我可以使用迭代列表
for item in list:
f.write(str(item))
but it writes the data to the text file as binary data. 但是它将数据作为二进制数据写入文本文件。
I just want to have each XYZ value comma separated with each row storing one XYZ value. 我只想让每个XYZ值逗号分隔,每一行存储一个XYZ值。 Any help is appreciated.
任何帮助表示赞赏。
np.savetxt
will write the list: 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
really saves an array, but converts the list to array if needed: 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]])
It then iterates over rows, and writes 然后,它遍历行并写入
f.write(fmt % tuple(row))
where fmt
is either the full string you provide or one constructed by replicating the shorter fmt
I provided. 其中
fmt
是您提供的完整字符串,或者是通过复制我提供的较短的fmt
构建的字符串。
Effectively savetxt
is doing: 实际上,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.