1

I have used this code first-

from scipy.io import loadmat 
data=loadmat(r"C:\Users\ansha\Downloads\HTS_C1_SN14_13.11.2019_02.mat")
print(data.keys())

and then i got this as an output-

dict_keys(['__header__', '__version__', '__globals__', 'EyePts_', 'JoyPts_', 'TrlNo_', 'M1EyeX_', 'M1EyeY_', 'M1Pupil_', 'M1JoyX_', 'M1JoyY_', 'cond_', 'RwdCue_', 'MagCue_', 'MLTrialStart_', 'MLTrialEnd_', 'TrialStart_', 'FixToggleON_', 'FixON_', 'AcqFix_', 'HoldFix_', 'Correct_', 'RewardONJ1_', 'RewardOFFJ1_', 'Abort_', 'EndOfTrial_', 'ITION_', 'ITIOFF_', 'STargetON_', 'AcqSTarget_', 'HoldSTarget_', 'SmRwdON_', 'SmRwdOFF_', 'LickCamON_', 'RewardCueON_', 'HoldRwdCue_', 'MagnitudeCueON_', 'HoldMagCue_', 'TwoTargetsON_', 'AcqRTarget_', 'HoldRTarget_', 'AcqLTarget_', 'HoldLTarget_', 'RewardONJ2_', 'RewardOFFJ2_', 'RewardONJ3_', 'RewardOFFJ3_', 'RewardONJ4_', 'RewardOFFJ4_', 'YRcue_pos_', 'WRcue_pos_', 'LT_pos_', 'RT_pos_', 'RT_col_', 'LT_col_', 'RCueCol_', 'JoyPosn_', 'LeftT_', 'RtT_', 'ReactionTime_', 'ReactionTimeP_'])

I am now lost, and i do not know how to convert this into a pandas dataframe and save it as csv. Please help!!!

2 Answers 2

3

Try Using:

from scipy.io import loadmat 
import pandas as pd
data = loadmat(r"C:\Users\ansha\Downloads\HTS_C1_SN14_13.11.2019_02.mat")
data  = {k:v for k, v in data.items() if k[0] != '_'}
df = pd.DataFrame({k: pd.Series(v[0]) for k, v in data.items()})  
df.to_csv("example.csv")
Sign up to request clarification or add additional context in comments.

5 Comments

it is giving me this error- NameError Traceback (most recent call last) Input In [5], in <cell line: 4>() 2 import pandas as pd 3 data=loadmat(r"C:\Users\ansha\Downloads\HTS_C1_SN14_13.11.2019_02.mat") ----> 4 mat={k:v for k,v in mat.items() if k[0]!="_"} 5 data=pd.DataFrame({k:pd.Series(v[0])for k ,v in mat.items()}) 6 data.to_csv("IITK.csv") NameError: name 'mat' is not defined
try now. I changed the variable name.
i think it worked but where do i find the csv file now? or how do i see the csv file? i am sorry i am just a newbie here!!!
oh wait, i now found it! thanks a ton for your help!!
@AnshBharadwaj if the answer is correct upvote it and mark as correct by clicking the tick under the down arrow
-2
import os
import scipy.io
import pandas as pd
import numpy as np

# Direct path to your Matlab folder
matlab_folder = r"your file path " #add the path to your file
output_folder = os.path.join(os.path.dirname(matlab_folder), "outputs")
os.makedirs(output_folder, exist_ok=True)

def to_dataframe(var_data, var_name):
    arr = np.array(var_data)
    if arr.ndim == 1:
        return pd.DataFrame({var_name: arr})
    elif arr.ndim == 2 and arr.shape[1] == 1:
        return pd.DataFrame({var_name: arr.ravel()})
    elif arr.ndim == 2:
        cols = [f"{var_name}_{i}" for i in range(arr.shape[1])]
        return pd.DataFrame(arr, columns=cols)
    else:
        flat = arr.reshape(arr.shape[0], -1)
        cols = [f"{var_name}_{i}" for i in range(flat.shape[1])]
        return pd.DataFrame(flat, columns=cols)

# Convert all .mat files inside the Matlab folder
for file in os.listdir(matlab_folder):
    if file.endswith(".mat"):
        file_path = os.path.join(matlab_folder, file)
        print(f"⚙ Processing {file_path}...")

        data = scipy.io.loadmat(file_path)
        clean_data = {k: v for k, v in data.items() if not k.startswith("")}

        base_name = os.path.splitext(file)[0]
        csv_path = os.path.join(output_folder, f"{base_name}.csv")
        xlsx_path = os.path.join(output_folder, f"{base_name}.xlsx")

        all_dfs = []

        with pd.ExcelWriter(xlsx_path, engine="openpyxl", mode="w") as writer:
            for var_name, var_data in clean_data.items():
                try:
                    df = to_dataframe(var_data, var_name)
                except Exception:
                    df = pd.DataFrame({var_name: [str(var_data)]})

                # Save each variable to its own Excel sheet
                df.to_excel(writer, sheet_name=var_name[:31], index=False)

                # Collect for CSV merge
                all_dfs.append(df)

        if all_dfs:
            final_df = pd.concat(all_dfs, axis=1)
            final_df = final_df.applymap(lambda x: x if np.isscalar(x) else str(x))
            final_df.to_csv(csv_path, index=False)

        print(f"✔ Converted {file} → {csv_path}, {xlsx_path}")

1 Comment

Welcome to Stack Overflow! Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.