Vofun Vofun - 3 months ago 5
Python Question

Putting 2 dimensional numpy arrays into a 3 dimensional array

I want to keep adding numpy arrays to another array in python.
let's say I have the following arrays:

arraytotal = np.array([])
array1 = np.array([1,1,1,1,1])
array2 = np.array([2,2,2,2,2])


and I want to append array1 and array2 into arraytotal. However, when I use:

arraytotal.append[array1]


it tells me:


'numpy.ndarray' object has no attribute 'append'


how can I append array1 and array2 into arraytotal?

Answer

You should append the arrays onto a regular python list and then convert the list to a numpy array at the end:

import numpy as np
total = []
for i in range(5,15):
    thisArray = np.arange(i)
    total.append(thisArray)
total = np.asarray(total)

That loop makes a 2D array; you'd nest loops to produce higher dimensional arrays.