Import struct with different data type to python dataframe

103 ビュー (過去 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 Center および File ExchangeCall Python from MATLAB についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by