YatShan
YatShan

Reputation: 444

How to load .mat file and convert it to .csv file?

I wanted to load .mat file and to convert it to .csv file.

This is for MacOS terminal, running python3.7. In the past I've loaded .csv and .dat files. Following is the code I wrote to write for above task.

mat_274 = load('ecgca274_edfm.mat')
T = struct2table(mat_274)
writetable(T, 'ecgca274_edfm.csv', 'Delimiter', ',')
print(mat_274)

After running the above code, I'm getting following error

Traceback (most recent call last):
  File "bayesian3.py", line 1, in <module>
    mat_274 = load('ecgca274_edfm.mat')
NameError: name 'load' is not defined

Can anyone help to correct errors or suggest a new way for this conversion task ? Thank you

Upvotes: 2

Views: 13295

Answers (2)

YatShan
YatShan

Reputation: 444

I have found the answer for my above question. Code Snippet is as follows.

import pandas as pd
from scipy.io import loadmat

data_dict = loadmat('ecgca274_edfm.mat')
data_array = data_dict['val']
data_array = data_array.transpose(1, 0)
df = pd.DataFrame(data_array,
                  columns=['ch'+str(n) for n in range(1,7)])

Rather than converting into csv, as I asked in the original question, I have converted it to a dataframe for further processing.

Upvotes: 3

Jason K Lai
Jason K Lai

Reputation: 1540

There is a function in scipy for this operation, as described on their documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html

import scipy.io
mat_274 = scipy.io.loadmat( 'ecgca274_edfm.mat' )

However, it is also very picky about the version of MATLAB used to generate the *.mat file. In the link above is the following warning:

v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.

You will need an HDF5 python library to read MATLAB 7.3 format mat files. 
Because scipy does not supply one, we do not implement the HDF5 / 7.3 interface here.

One potential way to get around this problem is by saving it as an older mat version in MATLAB. The following command should do this (in MATLAB):

save( 'ecgca274_edfm.mat', '-v7' )

Upvotes: 2

Related Questions