How to sampling for plotting spectogram EEG

Hello Guys , I want to plot some EEG signal that I obtained from a data set. But I’m new in scipy so my task is:

  1. Preprocess the EEG recordings by applying a high-pass filter above 1 Hz and a low-pass filter below 50 Hz.
  2. Downsample the EEG signal from 256 Hz to 128 Hz to improve computational efficiency.
  3. Plot the spectrogram for channels TP9 and TP10.

But I have a error " ValueError: “Length of values does not match length of index.”
Code:

# Extract the desired channels (TP9 and TP10)
channels = ['TP9', 'TP10']  
eeg_data = eeg_df[channels]

# Convert the timestamps to time in seconds
sampling_rate = 256  # Sampling rate of the EEG data in Hz
time_seconds = eeg_df['timestamps'] / sampling_rate

# Preprocess the EEG signals
for channel in channels:
    # Apply high-pass filter above 1 Hz and low-pass filter below 50 Hz
    b, a = signal.butter(4, [1, 50], btype='bandpass', fs=sampling_rate)
    eeg_data[channel] = signal.filtfilt(b, a, eeg_data[channel])
    
    # Downsample the signal from 256 to 128 Hz
    new_length = len(eeg_data[channel]) // 2
    eeg_data[channel] = signal.resample(eeg_data[channel], new_length)

# Define the parameters for the spectrogram
window = 'hann'  # Windowing function
nperseg = 128    # Length of each segment
noverlap = 64    # Overlap between segments
nfft = 128       # Number of points for the FFT

# Compute the spectrogram for each channel
frequencies, times, spectrogram_TP9 = signal.spectrogram(eeg_data['TP9'], fs=sampling_rate / 2, window=window, 
                                                         nperseg=nperseg, noverlap=noverlap, nfft=nfft)
_, _, spectrogram_TP10 = signal.spectrogram(eeg_data['TP10'], fs=sampling_rate / 2, window=window, 
                                            nperseg=nperseg, noverlap=noverlap, nfft=nfft)

So, i would like to know If I miss some step because when I want to implement my code it does not run and said the error that I mentioned before it.

1 Like

Hi Jose!

Do you mind posting the full traceback of the error, so we can see where it originates?

Hello, yes


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[58], line 17
     15     # Downsample the signal from 256 to 128 Hz
     16     new_length = len(eeg_data[channel]) // 2
---> 17     eeg_data[channel] = signal.resample(eeg_data[channel], new_length)
     19 # Define the parameters for the spectrogram
     20 window = 'hann'  # Windowing function

eeg_data[channel] is a column in a dataframe, right? So you are trying to assign fewer values to that column than it currently has. You cannot reduce the length of a dataframe this way.

Thanks @JoseMoranRodriguez for this amazing info. Actually I stucked somewhere to execute my code but your solution helped me a lot.