A Python list of Numpy Arrays to CSV?
<p>I have a Python list of Numpy arrays storing X, Y, Z coordinates - like this:</p>

<pre><code>[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])]
</code></pre>

<p>And I would like to get them into a CSV file so I can plot them in GIS software.  I am new to Numpy arrays and I keep getting errors using methods like numpy.ndarray.tofile().  </p>

<p>I can iterate the list using </p>

<pre><code>for item in list:
    f.write(str(item))
</code></pre>

<p>but it writes the data to the text file as binary data.<br>
I just want to have each XYZ value comma separated with each row storing one XYZ value. 
Any help is appreciated.</p>

<p><code>np.savetxt</code> will write the list:</p>

<pre><code>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
</code></pre>

<p><code>np.savetxt</code> really saves an array, but converts the list to array if needed:</p>

<pre><code>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]])
</code></pre>

<p>It then iterates over rows, and writes</p>

<pre><code>f.write(fmt % tuple(row))
</code></pre>

<p>where <code>fmt</code> is either the full string you provide or one constructed by replicating the shorter <code>fmt</code> I provided.</p>

<p>Effectively <code>savetxt</code> is doing:</p>

<pre><code>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
</code></pre>

python arrays csv numpy