Import struct with different data type to python dataframe

41 vues (au cours des 30 derniers jours)
rodologie
rodologie le 17 Août 2023
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.

Réponse acceptée

Daniele Sportillo
Daniele Sportillo le 21 Août 2023
Modifié(e) : Daniele Sportillo le 21 Août 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

Plus de réponses (0)

Catégories

En savoir plus sur Call MATLAB from Python dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by