I have the follwoing problem. I have a 3D array like
matrix = np.zeros((30,30,100))
where every entry is a coordinate and gets a value. So matrix [0][0][0]
is the coordinate x=0,y0,z=0 and has a value of 0. Now i want to store all the values in a csv like this where the first 3 rows are the coordinates and the 4th the corresponding value:
Is there a fast way with numpy to do this?
An array is used to store a collection of elements under a single name. We use the numpy module to deal with arrays in Python. We will discuss different methods on how to write array to CSV file. The to_csv () function exports a pandas DataFrame to a CSV file of the desired name.
A CSV file is a simple text file, with data separated by commas. It can represent tabular data and viewed as spreadsheets. An array is used to store a collection of elements under a single name. We use the numpy module to deal with arrays in Python.
Numpy.savetxt () is a method in python in numpy library to save an 1D and 2D array to a file. Syntax: numpy.savetxt (fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘, encoding=None)
To define a 3-d array we can use numpy.ones () method. In Python the numpy.ones () function fills values with one and it will always return a new numpy array of given shape. Here is the Syntax of numpy.ones () method
You could use pandas, it can both reshape the array and save it as csv.
import numpy as np
import pandas as pd
# create an example array
a = np.arange(24).reshape([2,3,4])
# convert it to stacked format using Pandas
stacked = pd.Panel(a.swapaxes(1,2)).to_frame().stack().reset_index()
stacked.columns = ['x', 'y', 'z', 'value']
# save to disk
stacked.to_csv('stacked.csv', index=False)
Otherwise, you can apply
np.ravel()
to your array and then restore indices using one of the recipes in this question.
I imagine you get the coordinates with the indices:
def iter_3D(matrix):
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
for k in range(matrix.shape[2]):
yield i, j, k
l = []
for i, j, k in iter_3D(matrix):
l.append('%d %d %d %d' %(str(indices_x(i, j, k)), str(indices_y(i, j, k)), str(indices_z(i, j, k)), str(matrix[i, j, k]))
with open('file.csv', 'w') as f:
f.write("\n".join(l))
More sophisticated solutions are possible, but this should be the core. Have a look at: csv io in the python docs or nditer if you want a more sophisticated iteration method or use pandas (takes a little time to get the hang out of it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With