Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert mat file to pandas dataframe

I want to convert this file to pandas dataframe.

import pandas as pd
import scipy.io
mat = scipy.io.loadmat('cardio.mat')
cardio_df = pd.DataFrame(mat)

I get this error : Exception: Data must be 1-dimensional

like image 842
Mohammad Mahdi KouchakYazdi Avatar asked Jul 10 '17 08:07

Mohammad Mahdi KouchakYazdi


People also ask

Can Python read a .MAT file?

Load data from a MAT-fileThe function loadmat loads all variables stored in the MAT-file into a simple Python data structure, using only Python's dict and list objects. Numeric and cell arrays are converted to row-ordered nested lists. Arrays are squeezed to eliminate arrays with only one element.

How do I open a .MAT file without MATLAB?

mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .


1 Answers

It seems mat is a dict containing X of shape (1831, 21), y with shape (1831, 1), and some metadata. Assuming X is the data and y are the labels for the same, you can stack them horizontally with np.hstack and load them into pandas:

In [1755]: mat = scipy.io.loadmat('cardio.mat')

In [1758]: cardio_df = pd.DataFrame(np.hstack((mat['X'], mat['y'])))

In [1759]: cardio_df.head()
Out[1759]: 
         0         1         2         3         4         5         6   \
0  0.004912  0.693191 -0.203640  0.595322  0.353190 -0.061401 -0.278295   
1  0.110729 -0.079903 -0.203640  1.268942  0.396246 -0.061401 -0.278295   
2  0.216546 -0.272445 -0.203640  1.050988  0.148753 -0.061401 -0.278295   
3  0.004912  0.727346 -0.203640  1.212171 -0.683598 -0.061401 -0.278295   
4 -0.100905  0.363595  1.321366  1.027120  0.141359 -0.061401 -0.278295   

In [1760]: cardio_df.shape
Out[1760]: (1831, 22)
like image 120
cs95 Avatar answered Sep 28 '22 08:09

cs95