Last active
April 4, 2022 12:42
-
-
Save eug/a3dce98d4c88b0934970ee7de8bb1ec5 to your computer and use it in GitHub Desktop.
Convert .mat to .csv file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
from scipy.io import loadmat | |
def mat2csv(file_mat, index=False): | |
mat = loadmat(file_mat, squeeze_me=True) | |
for colname in mat.keys(): | |
# ignore private column names | |
if colname.startswith("__"): | |
continue | |
for fieldname in mat[colname].dtype.names: | |
# ignore struct fields different from "data" | |
# rename or uncomment it to match your needs | |
if fieldname != "data": | |
continue | |
# get dataset values from "data" field for current column | |
element = mat[colname][fieldname].item() | |
# it could exist other instances (eg. str) and other dimensions (eg. 1D) | |
# update these lines if you need something different than this | |
if isinstance(element, np.ndarray): | |
if len(element.shape) == 2: | |
_, cols = element.shape | |
data = {f"x{i}" : element[:, i] for i in range(cols)} | |
pd.DataFrame(data).to_csv(f"{colname}.csv", index=False) | |
mat2csv("filename.mat") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi !
i used your code and changed line 31
no errors and was able to run the code
but it doesn't give me a csv file ?
can you add a path for csv