user4911648
user4911648

Reputation:

numpy append slices to two dimensional array to make it three dimensional

I have 5 numpy arrays with shape (5,5). What I want to achieve is to combine these 5 numpy arrays to one array of shape (5,5,5). My code looks like the following but does not work:

combined = np.empty((0, 5, 5), dtype=np.uint8)

for idx in range(0, 5):
    array = getarray(idx) # returns an array of shape (5,5)
    np.append(combined, img, axis=0)

I thought if I set the first axis to 0 it will append on this axis so that in the end the shape will be (5,5,5). What is wrong here?

Upvotes: 1

Views: 1059

Answers (2)

hpaulj
hpaulj

Reputation: 231425

I'd try:

A = np.array([getarray(idx) for idx in range(5)])

Or

alist = []
for idx in range(5):
   alist.append(getarray(idx))
A = np.array(alist)

Appending to a list is faster than appending to an array. The latter makes a totally new array - as you discovered.

dynamically append N-dimensional array - same issue, starting with different dimensions.

Upvotes: 0

user4911648
user4911648

Reputation:

I have figured it out by myself:

combined = np.empty((0, 5, 5), dtype=np.uint8)

for idx in range(0, 5):
    array = getarray(idx) # returns an array of shape (5,5)
    array array[np.newaxis, :, :]
    combined = np.append(combined, img, axis=0)
print combined.shape + returns (5,5,5)

Upvotes: 1

Related Questions