Import struct with different data type to python dataframe

조회 수: 33 (최근 30일)
rodologie
rodologie 2023년 8월 17일
편집: Daniele Sportillo 2023년 8월 21일
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.

채택된 답변

Daniele Sportillo
Daniele Sportillo 2023년 8월 21일
편집: Daniele Sportillo 2023년 8월 21일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by