Import struct with different data type to python dataframe

108 visualizzazioni (ultimi 30 giorni)
Hi,
I tried using python to load the data stored in a matlab struct - the struct i in a file attached.
Here is what I tried:
import scipy.io
import pandas as pd
mat = scipy.io.loadmat("file.mat")
data = mat["struct"]
Then, when I look to what is inside of 'data' I have this:
array([[(MatlabOpaque([(b'', b'MCOS', b'string', array([[3707764736],
[ 2],
[ 1],
[ 1],
[ 1],
[ 1]], dtype=uint32)) ],
dtype=[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]), MatlabOpaque([(b'', b'MCOS', b'datetime', array([[3707764736],
[ 2],
[ 1],
[ 1],
[ 2],
[ 2]], dtype=uint32)) ],
dtype=[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]), MatlabOpaque([(b'', b'MCOS', b'duration', array([[3707764736],
[ 2],
[ 1],
[ 1],
[ 3],
[ 3]], dtype=uint32)) ],
dtype=[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]), array([[1.0082, 1.0102, 1.01 ]])) ]],
dtype=[('Name', 'O'), ('init', 'O'), ('age', 'O'), ('measure', 'O')])
Hoy can I get the data stored in the mat file then?
Thanks in advance for your help.

Risposta accettata

Daniele Sportillo
Daniele Sportillo il 21 Ago 2023
Modificato: Daniele Sportillo il 21 Ago 2023
Hi,
first of all, I suggest you rename the variable struct in your file: struct is a MATLAB data type, and that may create problems with your code.
Then, you can use the MATLAB Engine API for Python (Call MATLAB from Python - MATLAB & Simulink (mathworks.com)) to load your .mat file.
import matlab.engine
eng = matlab.engine.start_matlab()
s = eng.load('file.mat')
You'll be able to directly use some of the fields in your structure. For other fields (e.g., datetime) you would need to first convert them
import matlab.engine
from datetime import datetime
eng = matlab.engine.start_matlab()
s = eng.load('file.mat')
print(s['struct']['measure'])
print(datetime.strptime(eng.string(s['struct']['init']),'%d-%b-%Y %H:%M:%S'))
Hope this helps.
Best,
Daniele

Più risposte (0)

Prodotti


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by