日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python读取mat数据是字典形式如何转化为矩阵_mat2json, python读取mat成字典, 保存json...

發(fā)布時(shí)間:2025/3/15 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python读取mat数据是字典形式如何转化为矩阵_mat2json, python读取mat成字典, 保存json... 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

python程序, 實(shí)現(xiàn)matlab的.mat格式轉(zhuǎn)化為dict / json .

第一個(gè)參數(shù)mat_path代表需要轉(zhuǎn)化的mat路徑;

第二個(gè)參數(shù), 如果需要把字典序列化成json, 添加這一參數(shù), 代表json存放位置;

返回值: 轉(zhuǎn)化好的字典

import os

import json

import scipy.io as spio

import pandas as pd

def loadmat(filename):

'''

this function should be called instead of direct spio.loadmat

as it cures the problem of not properly recovering python dictionaries

from mat files. It calls the function check keys to cure all entries

which are still mat-objects

'''

data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)

return _check_keys(data)

def _check_keys(dict):

'''

checks if entries in dictionary are mat-objects. If yes

todict is called to change them to nested dictionaries

'''

for key in dict:

if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):

dict[key] = _todict(dict[key])

return dict

def _todict(matobj):

'''

A recursive function which constructs from matobjects nested dictionaries

'''

dict = {}

for strg in matobj._fieldnames:

elem = matobj.__dict__[strg]

if isinstance(elem, spio.matlab.mio5_params.mat_struct):

dict[strg] = _todict(elem)

else:

dict[strg] = elem

return dict

def mat2json(mat_path=None, filepath = None):

"""

Converts .mat file to .json and writes new file

Parameters

----------

mat_path: Str

path/filename .mat存放路徑

filepath: Str

如果需要保存成json, 添加這一路徑. 否則不保存

Returns

返回轉(zhuǎn)化的字典

-------

None

Examples

--------

>>> mat2json(blah blah)

"""

matlabFile = loadmat(mat_path)

#pop all those dumb fields that don't let you jsonize file

matlabFile.pop('__header__')

matlabFile.pop('__version__')

matlabFile.pop('__globals__')

#jsonize the file - orientation is 'index'

matlabFile = pd.Series(matlabFile).to_json()

if filepath:

json_path = os.path.splitext(os.path.split(mat_path)[1])[0] + '.json'

with open(json_path, 'w') as f:

f.write(matlabFile)

return matlabFile

總結(jié)

以上是生活随笔為你收集整理的python读取mat数据是字典形式如何转化为矩阵_mat2json, python读取mat成字典, 保存json...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。