0

I am trying to loop my function by the rows of my dataframe. I am sharing an example of it, actual data consist of about 1000 rows and 8 columns. Is it possibel to run a for loop to get this? I would rather not use "pandas apply"

import pandas as pd
import numpy as np


weights = {'W1': [0.25,0.25,0.25,0.25],
    'W2': [0.2,0.2,0.2,0.4],
     'W3': [0.2,0.3,0.5,0.0]  
    }


 df = pd.DataFrame(weights, columns = ['W1', 'W2', 'W3'])

 ER = np.array([0.08, 0.09, 0.10])




def PortfolioReturn_Calc(weights, ER):
  portfolio_ret = (ER * weights).sum(axis=1)
  return portfolio_ret


for i in range(len(weights)):
  Ws = rows.df
  PortfolioReturn_Calc(Ws, ER)
skatip
  • 15
  • 6
  • Why do you not want to use `pd.apply`? In general it is more efficient and encouraged to use internal routines rather than iterating over a dataframe. Does [this](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) maybe help? – David Wierichs Jun 10 '20 at 20:53
  • Because I will be adding this to another function afterwards. I believe I can do it better if it is a for loop. Is it possibe to do it with a loop? – skatip Jun 10 '20 at 20:59
  • Does the link not help with building the for loop? – David Wierichs Jun 10 '20 at 21:01
  • In the example what would be the desired output, if you want the rows: – Dayannex Jun 10 '20 at 21:40
  • For the function "PortflioReturn_Calc" weights should come from rows and ER is given. So it should be sumproduct of each row and ER. I just want to loop and find this for each row – skatip Jun 11 '20 at 05:28
  • link does not help. My functions is self defined. So I am not sure how to apply or loop through this. – skatip Jun 11 '20 at 07:19

1 Answers1

0

If you want to loop the COLUMNS:

for  key, val in weights.items():
      Ws = val
      print(Ws)
      print(PortfolioReturn_Calc(Ws, ER))
skatip
  • 15
  • 6
Dayannex
  • 51
  • 3
  • Thanks but this is looping through the column not the row. Since ER is 3 dimensional and columns are 4 it is not getting a result. My answer should be like this and so on for each row. 0 > 0.25 * 0.08 +0 .2* 0.09 + 0.2 * 0.10 – skatip Jun 11 '20 at 07:01