Home > database >  looping through arrays and dataframs
looping through arrays and dataframs

Time:10-30

Say I have nested array that contains 10 rows (and 10 columns for example). I want to divide the entry in each row by the corresponding entry in row above. Thus my output would be an array or dataframe or 9 rows. This is what I tried and it doesn't work because I am not correctly iterating through the rows. stock_prices is a dataframe.

stock_returns = []
sp = np.array(stock_prices)

for i in sp:
     sr = sp[i,:]/sp[i-1,:]
     print(sr)

CodePudding user response:

stock_returns=[]
sp = np.array(stock_prices)

for i in range(1,sp.shape[0])::
     sr = sp[i,:]/sp[i-1,:]
     stock_returns.append(sr)
stock_returns=np.array(stock_returns)

CodePudding user response:

This code saves the calculated values to the np array stock_returns (which is first created with the right shape to have enough space):

sp = np.array(stock_prices)
stock_returns = np.empty((sp.shape[0]-1, sp.shape[1]))

for i in range(1, sp.shape[0]):
    stock_returns[i-1] = sp[i, :]/sp[i-1, :]

print(stock_returns)
  • Related