title: How to use a faster loop than iterrows for the following code?
body: <p>I have a function that calculates the return of prices on a slice of the <code>return_df</code> dataframe and a separate loop that calculates standard deviations again on a sliced dataframe. I can run both and calculate the result right now with <code>iterrows</code> method. I have tried to apply the function to speed it up and even read about pandas/numpy vectorization but I get <code>nan</code> values instead. Is there a way to run this code faster? Any help is appreciated.</p>
  
  <pre><code>#sigma calculation function
  def sigma_calculation(sample_trade):
  
      trade_index = sample_trade.index[0]
      sample_return_lst=[]
      eurusd_return_lst=[]
      for i, row in return_df[trade_index-28:trade_index:1].iterrows():
          sample_return_lst.append(return_df.iloc[i,0] * sample_trade.iloc[0,1])
          eurusd_return_lst.append(return_df.iloc[i,1] * sample_trade.iloc[0,1])
  
      stats_df = pd.DataFrame(
      {'Asset Total Return'       : sample_return_lst,
       'Reference Total Return'   : eurusd_return_lst
       })  
  
      sigma_trade = stats_df['Asset Total Return'].std()
      sigma_eurusd = stats_df['Reference Total Return'].std()
  
      d_lev = sigma_trade/sigma_eurusd
  
      return d_lev
  
  #running the sigma_calculation function for 45 rows from the return_df dataframe and creating a separate df from it
  d_lev_lst = []
  for i, row in return_df[4433::1].iterrows():
      d_lev_lst.append(sigma_calculation(return_df.iloc[[i]]))
  
  d_lev_df = pd.DataFrame({'D-Leverage' : d_lev_lst})
  </code></pre>
  
  <p>This is what I tried for the second part (running sigma_calculation on 45 rows):</p>
  
  <pre><code>d_lev_df = pd.DataFrame(
      {'D-Leverage'   : return_df['Asset Return'].iloc[4433::1].apply(lambda row: sigma_calculation(return_df.iloc[[row]])),
      })
  </code></pre>