Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Storing values in a 3D array to csv

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:

enter image description here

Is there a fast way with numpy to do this?

like image 751
Varlor Avatar asked Oct 20 '17 15:10

Varlor


People also ask

How to write array to CSV file in Python?

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.

What is the difference between a CSV file and an array?

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.

How do I save a NumPy array to a file?

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)

How to define a 3-D array in Python?

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


2 Answers

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.

like image 200
David Dale Avatar answered Oct 24 '22 02:10

David Dale


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).

like image 33
Skyy2010 Avatar answered Oct 24 '22 01:10

Skyy2010