title: Python: Is there a way to apply a function separately on all columns of a dataframe specified in a list? Pyfinance package
body: <p>I would appreciate, if someone could give a me good answer, as I am not moving forward currently. Neither any resources helped my and my tries to create a loop failed. </p>
  
  <p>I have a big dataframe of stock returns, I tried to create a test dataset of it below. The used function to derive rolling betas on the stock (vs. market) returns works well. However, I don't manage to create a function to apply it on all/selected columns separately. </p>
  
  <p>I would be interested in two solutions: </p>
  
  <p><strong>i)</strong> which helps me to apply/loop the ols.PandasRollingOLS function to each column of the dataframe seperately</p>
  
  <p><strong>ii)</strong> and the other to solely run the ols.PandasRollingOLS function seperately over columns  specified in a list </p>
  
  <pre><code>import pandas as pd
  
  # intialise data 
  data = {'Market':[0.03, -0.01, 0.01, -0.01],
          'Stock1':[0.01, -0.02, 0.03, -0.02],
          'Stock2':[0.01, -0.011, 0.01, -0.011],
          'Stock3':[0.01, -0.011, 0.01, -0.011], 
          'Stock4':[0.02, -0.1, 0.02, 0.09],
          'Stock5':[-0.01, 0.01, 0.01, 0.005]}
  
  list_stocks = ["Stock1", "Stocks2", "Stock3"]
  
  # Create DataFrame
  df = pd.DataFrame(data)
  
  
  </code></pre>
  
  <p>The following code yields the right results, but given the size of the dataframe I cannot work with this solution for the dataset: </p>
  
  <pre><code>
  #!pip3 install pyfinance
  from pyfinance import ols
  
  y=df["Market"]
  w = 2 
  roll_beta["Stock1"] = ols.PandasRollingOLS(y=y, x=df[["Stock1"]], window=w).beta["Stock1"]
  roll_beta["Stock2"] = ols.PandasRollingOLS(y=y, x=df[["Stock2"]], window=w).beta["Stock2"]
  roll_beta["Stock3"] = ols.PandasRollingOLS(y=y, x=df[["Stock3"]], window=w).beta["Stock3"]
  
  
  print(roll_beta)
  $     Stock1    Stock2    Stock3
  1  1.333333  1.904762  1.904762
  2  0.400000  0.952381  0.952381
  3  0.400000  0.952381  0.952381
  
  </code></pre>