简体   繁体   中英

Appending elements to a numpy nd array

I have initialized a numpy nd array like the following

arr =  np.zeros((6, 6))

This empty array is passed as an input argument to a function,

def fun(arr):
    arr.append(1) # this works for arr = [] initialization
    return arr

for  i in range(0,12):
     fun(arr) 

But append doesn't work for nd array. I want to fill up the elements of the nd array row-wise. Is there any way to use a python scalar index for the nd array? I could increment this index every time fun is called and append elements to arr

Any suggestions?

In [523]: arr = np.zeros((6,6),int)                                                            
In [524]: arr                                                                                  
Out[524]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])
In [525]: arr[0] = 1                                                                           
In [526]: arr                                                                                  
Out[526]: 
array([[1, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])
In [527]: arr[1] = [1,2,3,4,5,6]                                                               
In [528]: arr[2,3:] = 2                                                                        
In [529]: arr                                                                                  
Out[529]: 
array([[1, 1, 1, 1, 1, 1],
       [1, 2, 3, 4, 5, 6],
       [0, 0, 0, 2, 2, 2],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

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