Python DataFrame转Matlab .mat文件转换失败求助
I’ve dealt with this exact headache when working with EEG datasets—getting pandas DataFrames to play nice with MATLAB’s .mat format can trip you up if you don’t account for how each tool structures numerical data. Let’s break down a reliable solution:
Step 1: Validate Your Data Import First
Before jumping into conversion, double-check that your DataFrame is loaded correctly. Run:
print(MyDataFrame.info()) print(MyDataFrame.head())
Ensure your EEG channels are all numeric (dtype float64 works best for MATLAB) and there are no unexpected string values or missing data that could break the conversion. If you have NaNs, fill them with a sensible value first (e.g., MyDataFrame = MyDataFrame.fillna(0) for EEG baseline noise).
Step 2: Convert DataFrame to Numpy Arrays (Not List Dictionaries)
The mistake most people make is converting the DataFrame to a dictionary of lists—MATLAB interprets lists as cell arrays, which isn’t ideal for numerical EEG data. Instead, convert columns to numpy arrays and package them into a dictionary that scipy can handle cleanly:
import scipy.io import pandas as pd # Your original data import MyDataFrame = pd.read_csv("data.txt", sep=';', decimal='.') # Option 1: Save each column as a separate variable in the .mat file mat_dict = {} for col_name in MyDataFrame.columns: # Convert column to float64 numpy array (MATLAB's preferred numeric type) mat_dict[col_name] = MyDataFrame[col_name].to_numpy(dtype='float64') # Option 2: Save the entire dataset as a single 2D matrix + column names (better for EEG) mat_dict['eeg_matrix'] = MyDataFrame.to_numpy(dtype='float64') mat_dict['channel_labels'] = MyDataFrame.columns.tolist() # Save to .mat file scipy.io.savemat('eeg_output.mat', mat_dict)
Step 3: Verify in MATLAB
Load the file in MATLAB to confirm it worked:
loaded_data = load('eeg_output.mat'); % Check the matrix dimensions (should match your DataFrame's rows x columns) size(loaded_data.eeg_matrix) % View channel labels loaded_data.channel_labels
Why Your Original Approach Failed
When you convert a DataFrame to a dictionary of lists, scipy’s savemat translates those lists into MATLAB cell arrays instead of dense numerical matrices. EEG data is almost always used as a numeric matrix in MATLAB, so this structure mismatch was likely causing your conversion issues. Using numpy arrays ensures the data stays in the numerical format MATLAB expects.
内容的提问来源于stack exchange,提问作者ArnoBen

