Reading Matlab data file in Python, need to export to CSV

I read a Matlab file containing a large number of arrays as a dataset, in Python, storing the Matlab dictionary under the variable name mat with the command:

mat = loadmat('Sample Matlab Extract.mat')

Is there a way I can use the Python function to write to the csv function to save this Matlab dictionary variable, which I read in Python as a comma-delimited file?

 with open('mycsvfile.csv','wb') as f: w = csv.writer(f) w.writerows(mat.items()) f.close() 

creates a CSV file with one column containing the array names in the dictionary, and then another column containing the first element of each corresponding array. Is there a way to use a command like this to get all the relevant elements inside arrays inside the mat dictionary variable?

+6
source share
2 answers

The scipy.io.loadmat function creates a dictionary that looks something like this:

 {'__globals__': [], '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI, Created on: Wed Sep 24 16:11:51 2014', '__version__': '1.0', 'a': array([[1, 2, 3]], dtype=uint8), 'b': array([[4, 5, 6]], dtype=uint8)} 

It looks like you want to make a CSV file with keys "a", "b", etc. as column names and their corresponding arrays as data associated with each column. If so, I would recommend using pandas to create a beautifully formatted dataset that can be exported to a CSV file. First, you need to clear the comments of your dictionary members (all keys starting with "__"). Then you want to turn each item value into a dictionary into a pandas.Series object. Then the dictionary can be turned into a pandas.DataFrame object, which can also be saved as a CSV file. Your code will look like this:

 import scipy.io import pandas as pd mat = scipy.io.loadmat('matex.mat') mat = {k:v for k, v in mat.items() if k[0] != '_'} data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.iteritems()}) data.to_csv("example.csv") 
+5
source

This is the right solution to convert any .mat file to a CSV file. Try

  import scipy.io import numpy as np data = scipy.io.loadmat("file.mat") for i in data: if '__' not in i and 'readme' not in i: np.savetxt(("file.csv"),data[i],delimiter=',') 
+3
source

Source: https://habr.com/ru/post/972257/


All Articles