Home > OS >  How to append numpy array as rows when the initial array is empty?
How to append numpy array as rows when the initial array is empty?

Time:12-07

I have a function that returns an array, I want to append several of these arrays and get the mean of each row.

Basic code I want:

arr = []
for i in range(0,3):
    b = get_array()
    arr.append(b)
    
b_mean = np.mean(b, axis=0)

What I hope to achieve with it:

'''
arr = np.array([])
b0 = np.array([3, 3, 3, 5])
b1 = np.array([6, 6, 5, 7])
b3 = np.array([1, 2, 3, 4])

desired_result = np.array([[3, 3, 3, 5],
                           [6, 6, 5, 7],
                           [3, 2, 7, 3]])

desired_result_average = np.array([4, 3.66, 5, 5])
'''

I think I can achieve this by first making the array a regular list, and later converting the list back to a numpy array so I can get the mean. But this seems like a weird way...

I tried np.concatenate, np.insert, np.vstack. But these all require an initial array of the dimensions as the other arrays..

CodePudding user response:

No need to be aware of the shape of b.

arrs = []
for i in range(0,3):
    b = get_array()
    arrs.append(b)

arr = np.vstack(arrs)

b_mean = np.mean(arr, axis=0)
  • Related