-
-
Save eug/a3dce98d4c88b0934970ee7de8bb1ec5 to your computer and use it in GitHub Desktop.
| 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") |
Hi @dial2hari, these are hardcoded key values, in other words, it is not a generic approach to solve the problem.
You can use the loadmat function alone and then adapt the output as you need it. Take this gist as a guideline to adapt your output, not as the final solution.
can i use this code to convert my mat file to csv? how can mat file located into code?
can i use this code to convert my mat file to csv?
Probably, yes.
how can mat file located into code?
I just updated the gist. You must replace line 31 specifying your filename.
Hi @dial2hari, these are hardcoded key values, in other words, it is not a generic approach to solve the problem. You can use the loadmat function alone and then adapt the output as you need it. Take this gist as a guideline to adapt your output, not as the final solution.
Thanks, Eug...
can i use this code to convert my mat file to csv?
Probably, yes.
how can mat file located into code?
I just updated the gist. You must replace line 31 specifying your filename.
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
for col_id in range(len(mat['X'][0])):
what is 'X' here ??
for row in mat['y']:
what is 'y' here ??