sumitpal0593
sumitpal0593

Reputation: 334

How to append a set of numpy arrays while inside a for loop?

The thing I want to do is, I want append a set of numpy arrays one after the other while in a for loop. So whenever a new array comes, the new array will be appended to the older one. The code I have written is as follows:

def joinArray(highest_score, seq):

      seq1 = np.array([])
      seq2 = np.array([])
      seq3 = np.array([])
      seq4 = np.array([])
      seq5 = np.array([])

      if(highest_score == 1):
    
            seq1 = np.concatenate((seq1,seq), axis = 1)
    
            return(seq1)

      if(highest_score == 2):
    
            seq2 = np.concatenate((seq2,seq), axis = 1)

      if(highest_score == 3):
    
            seq3 = np.concatenate((seq3,seq), axis = 1)

      if(highest_score == 4):
    
            seq4 = np.concatenate((seq4,seq), axis = 1)

      if(highest_score == 5):
    
            seq5 = np.concatenate((seq5,seq), axis = 1)

def sequenced(dat):

      for i in range(0,10):
    
          passvalue = joinArray(highest_index[i]+1,dat)



for i in range(0,38,2):

       H = Data2.iloc[:, i:i+2]
       H = H.dropna()

       scaler = StandardScaler()
       Sdatad1 = scaler.fit_transform(H)

h1 = sequenced(Sdatad1)

However, on running this code, I get this error:

   AxisError: axis 1 is out of bounds for array of dimension 1

I have tried np.append(), np.vstack() also but all end up in errors. Is there a way this problem can be solved?

Upvotes: 0

Views: 151

Answers (1)

chazecka
chazecka

Reputation: 151

First of all, you are redefining your arrays each run. I used a little trick with global keyword here, but you can easily convert the code into OOP, if you are familiar with it. Secondly, in order for python to append array to array (and not number after number), you have to define your array as 1- dimension array. I simplified your joinArray function, but you should be able to continue working with it.

import numpy as np

highest_score_HMM = 1

seq1 = np.empty((0, 1))
seq2 = np.empty((0, 1))
seq3 = np.empty((0, 1))
seq4 = np.empty((0, 1))
seq5 = np.empty((0, 1))


def joinArray(highest_score, seq):

    global seq1, seq2, seq3, seq4, seq5

    if(highest_score == 1):
        seq1 = np.concatenate((seq1, seq))

    if(highest_score_HMM == 2):
        seq2 = np.concatenate(seq2, seq)

    if(highest_score_HMM == 3):
        seq3 = np.concatenate(seq3, seq)

    if(highest_score_HMM == 4):
        seq4 = np.concatenate(seq4, seq)

    if(highest_score_HMM == 5):
        seq5 = np.concatenate(seq5, seq)


seq = np.array([[2]])
joinArray(1, seq)
joinArray(1, seq)
joinArray(1, seq)

print(seq1)

result: [[2.][2.][2.]]

result[0]: [2.]

Upvotes: 1

Related Questions