Building up an array in numpy/scipy by iteration in Python?

后端 未结 3 857
我在风中等你
我在风中等你 2020-12-30 00:14

Often, I am building an array by iterating through some data, e.g.:

my_array = []
for n in range(1000):
  # do operation, get value 
  my_array.append(value)         


        
3条回答
  •  無奈伤痛
    2020-12-30 00:49

    If i understand your question correctly, this should do what you want:

    # the array passed into your function
    ax = NP.random.randint(10, 99, 20).reshape(5, 4)
    
    # just define a function to operate on some data
    fnx = lambda x : NP.sum(x)**2
    
    # apply the function directly to the numpy array
    new_row = NP.apply_along_axis(func1d=fnx, axis=0, arr=ax)
    
    # 'append' the new values to the original array
    new_row = new_row.reshape(1,4)
    ax = NP.vstack((ax, new_row))
    

提交回复
热议问题