Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a 3D Numpy array to a CSV file

I have a 3D Numpy array with the shape [1953,949,13]. I want to write it to a CSV file where each row should contain a 2D array of shape [949 13] and csv file should contain 1953 rows. I tried np.savetext and it supports only 1D and 2D arrays. Then I tried line by line writing to a CSV but it requires each matrix to be converted to a string. How can I get this done in python? My requirement is different from the question Storing values in a 3D array to csv

like image 819
rpb Avatar asked May 22 '18 02:05

rpb


People also ask

How do I import a NumPy array into CSV?

Python NumPy read CSV into 2d NumPy arraytxt() and open() functions to load a CSV file into a 2Dimension NumPy Array. Call open file to open the CSV text file Use numpy. loadtxt( CSV file, delimiter) with the file as the result of the previous step and delimiter as “,” to return the data in a two-dimensional NumPy.

How do I convert an array to a CSV file?

We can write an array to a CSV file by first converting it to a DataFrame and then providing the CSV file's path as the path argument using the Dataframe. to_csv() method. Since the default value of the sep argument is , , we have to provide the DataFrame and the path argument to the Dataframe. to_csv() method.

How do you read a 3D matrix in Python?

import numpy >>> a = numpy. loadtxt('testfile') >>> a array([[ 1., 2.], [ 3., 4.], [ 11., 12.], [ 13., 14.]]) >>> a. reshape((2, 2, 2)) array([[[ 1., 2.], [ 3., 4.]], [[ 11., 12.], [ 13., 14.]]])


2 Answers

I'm not sure if it's the best way to doing it, but I faced the same problem and here's how I solved it.

import csv
import numpy as np
fil_name = 'file'
example = np.zeros((2,3,4))
example = example.tolist()
with open(fil_name+'.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerows(example)

#to read file you saved
with open(fil_name+'.csv', 'r') as f:
  reader = csv.reader(f)
  examples = list(reader)

print(examples)
nwexamples = []
for row in examples:
    nwrow = []
    for r in row:
        nwrow.append(eval(r))
    nwexamples.append(nwrow)
print(nwexamples)
like image 192
Abdullah Abdelmonem Avatar answered Oct 06 '22 20:10

Abdullah Abdelmonem


I used this method instead, not aware of any better method:

# reshaping the array from 3D matrice to 2D matrice.
arrReshaped = arr.reshape(arr.shape[0], -1)
# saving reshaped array to file.
np.savetxt(filename, arrReshaped)
# retrieving data from file.
loadedArr = np.loadtxt(filename)
# This loadedArr is a 2D array, therefore we need to convert it to the original array shape.
# reshaping to get original matrice with original shape.
loadedOriginal = loadedArr.reshape(loadedArr.shape[0], loadedArr.shape[1] // arr.shape[2], arr.shape[2])
like image 36
Chetan Avatar answered Oct 06 '22 19:10

Chetan