简体   繁体   中英

Trying to append new columns in a numpy array using a for loop

I am trying to add new columns using the average of old columns, but I don't know how to loop through the columns from the weights array and append them to the class2 array.

class1 = weights[:,sort[popsize-1]]

for x in range(1,avgmating+1):
  new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))/2
  class2 = np.hstack((class2,new))

NameError: name 'class2' is not defined

How can I define Class2 and then add the "new" array to it in each iteration?

for x in range(1,avgmating+1):
  new = (class1 + np.array(weights[:,sort[popsize - 1 -x]]))/2
  if x == 1:
    class2 = new
  else:
    class2 = np.hstack((class2,new))

That works but I'm sure there is a faster way...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM