Skip to content

Instantly share code, notes, and snippets.

@techedlaksh
Created March 21, 2017 23:07
Show Gist options
  • Save techedlaksh/9001039bf54ba9d8aec3ad7f5d8bfd08 to your computer and use it in GitHub Desktop.
Save techedlaksh/9001039bf54ba9d8aec3ad7f5d8bfd08 to your computer and use it in GitHub Desktop.
Converting mat files to csv using python, scipy and pandas
import scipy.io
import pandas as pd
mat = scipy.io.loadmat('file.mat')
mat = {k:v for k, v in mat.items() if k[0] != '_'}
data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.iteritems()})
data.to_csv("example.csv")
@AmrMoursi1
Copy link

import scipy.io
import pandas as pd

mat = scipy.io.loadmat('file.mat')
mat = {k:v for k, v in mat.items() if k[0] != '_'}
data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.items()})
data.to_csv("example.csv")

This should work. use items() instead of iteritems()

Executing the above code causes the following error:
Traceback (most recent call last): File "mat2csv.py", line 6, in <module> data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.iteritems()}) AttributeError: 'dict' object has no attribute 'iteritems'
Changed mat.iteritems() to mat.items() and then it works. (as Python 3 renamed iteritems to items)

thanks for your explanation, it is working now but this code return only single row of data what should i do to get entire data in format of dataframe , thanks in advanc.

@ioarun
Copy link

ioarun commented May 23, 2023

import scipy.io
import pandas as pd

mat = scipy.io.loadmat('file.mat')
mat = {k:v for k, v in mat.items() if k[0] != '_'}
data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.items()})
data.to_csv("example.csv")

This should work. use items() instead of iteritems()

Executing the above code causes the following error:
Traceback (most recent call last): File "mat2csv.py", line 6, in <module> data = pd.DataFrame({k: pd.Series(v[0]) for k, v in mat.iteritems()}) AttributeError: 'dict' object has no attribute 'iteritems'
Changed mat.iteritems() to mat.items() and then it works. (as Python 3 renamed iteritems to items)

That's what I said.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment