Anupa Kulathunga
Anupa Kulathunga

Reputation: 31

How to create a 3d array in python using a data frame values?

I was trying to create a 3d array using a stock price dataset to get data of 30 min of time frame as one block in my 3d array. I coded as below:

x = []
for i in range(30,10000):
    x.append([])
    for j in range(i-30,i):
        x[i-30].append([])
        for k in range(0,4):
            x[i-30][j].append(df_prices.iloc[j,k]) 

but that shows an error

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-186-3509d316acf5> in <module>
      5         x[i-30].append([])
      6         for k in range(0,4):
----> 7             x[i-30][j].append(df_prices.iloc[j,k])
      8     #break

IndexError: list index out of range

but when I break the first for function as follows

x = []
for i in range(30,10000):
    x.append([])
    for j in range(i-30,i):
        x[i-30].append([])
        for k in range(0,4):
            x[i-30][j].append(df_prices.iloc[j,k])    
    break

I can get the first block of the array size of (1,30,4). But I want to get all the blocks of 9970 by iterating the function 30 to 10000. So how can I do that?

Upvotes: 1

Views: 63

Answers (1)

Anupa Kulathunga
Anupa Kulathunga

Reputation: 31

Finally got it:😋

x = []
for i in range(30,10000):
    arr=np.array(df_prices.iloc[i-30:i,])
    x.append([])
    for j in range(0,30):
        x[i-30].append([])
        for k in range(0,4):
            x[i-30][j].append(arr[j,k])    

This worked well!!!

Upvotes: 1

Related Questions