title: How do I calculate PSD, Median Frequency and Mean Frequency in python?
body: <p>I am trying to extract frequency features from EMG Data on python with a sliding window. I do not have too much knowledge on frequency analysis, so I apologize in advance if I've got some wrong concepts.</p>
  
  <p>I am trying to follow the definitions from this website:</p>
  
  <p><a href="https://i.stack.imgur.com/udOFg.png" rel="nofollow noreferrer">MDF</a></p>
  
  <p><a href="https://www.intechopen.com/books/computational-intelligence-in-electromyography-analysis-a-perspective-on-current-applications-and-future-challenges/the-usefulness-of-mean-and-median-frequencies-in-electromyography-analysis" rel="nofollow noreferrer">more information</a></p>
  
  <p>My questions are whether I am performing the calculations right, and if not how can I proceed to calculate them? </p>
  
  <pre><code>Windows_Size = 0.125 
  Overlap = 0.5 
  Bins = 256 
  
  START, END = df_filtered['Time'].min(), df_filtered['Time'].max()
  Fs = 2000 #EMG Sampling Frequency
  P = 1.0 / Fs
  
  Windows = np.arange(START + Windows_Size, END, Windows_Size * (1 - Overlap))
  FREQ = []
  
  for w in WINDOWS:
    win_start, win_end = w - Windows_Size, w
  
    for var in ['Biceps_Femoris_Sq_Correct']:
      value = df_filtered.loc[(win_start &lt;= df_filtered['Time']) &amp; (df_filtered['Time'] &lt; win_end), var].values
  
      fft = np.fft.fft(value * np.hamming(value.shape[0]), n=Bins)[1:Bins//2]
      freq = np.fft.fftfreq(Bins, P)[1:Bins//2]
      amp = np.abs(fft)
  
      energy = amp ** 2 # Is this the right way to calculate power spectrum? 
  
      median_freq = energy/2 
      #mean_freq = EMG power spectrum is divided into two regions with equal 
      #amplitude... is this right?
  
      mean_freq = np.sum(energy * freq) / np.sum(energy) 
  </code></pre>
  
  <p>Average frequency which is calculated as the sum of product of the EMG power 
  spectrum, and the frequency divided by the total sum of the power spectrum. Is this the right way to calculate mean frequency? </p>