1

I cannot stack numpy arrays over new dimension because of the following problem:

>>> a = np.zeros(shape=(100,100))
>>> b = np.zeros(shape=(100,100))
>>> c = np.stack((a, b))
>>> c.shape
(2, 100, 100)
>>> d = np.zeros(shape=(100,100))
>>> c = np.stack((c, d))
Traceback (most recent call last):
  File "/lib/python3.7/site-packages/numpy/core/shape_base.py", line 426, in stack
    raise ValueError('all input arrays must have the same shape')
ValueError: all input arrays must have the same shape

The way I intend to use it in a loop is:

final = None
for next_mat in mats:
    final = next_mat if final is None else np.stack((final, next_mat))

How do I achieve it? Thank you!

1
  • np.stack adds a new dimension each time you use it. And yes, it is very picky about the shape all all the input arrays. Commented May 5, 2020 at 16:45

2 Answers 2

1

I would rather store all the arrays and stack once:

cum_arr = []
for next_mat in mats:
    cum_arr.append(next_mat)

np.stack(cum_arr)

Or, if you have the mats list:

np.stack(mats)
Sign up to request clarification or add additional context in comments.

Comments

1

Since stack expects all inputs to be of the same shape, if you want to stack during each loop, you can use vstack instead. You also need to expand dimensions to (1,100,100) from (100,100).

final = None
for next_mat in mats:
    next_mat = np.expand_dims(next_mat, 0)
    final = next_mat if final is None else np.vstack((final, next_mat))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.