0

I've seen the numpy deprecation message, "FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple" appear in various threads but don't see the most pythonic way to address it for my simple situation of a three-dimensional array:

import numpy as np
X=np.random.rand(3,4,5)
Y= np.vstack(X[:, :, x].T for x in range(1,3)) # vertically stack X[:,:,0], X[:,:,1], etc.

The resulting error message is

Warning (from warnings module): File "<pyshell#2>", line 1 FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.

1
  • 4
    Y= np.vstack([X[:, :, x].T for x in range(1,3)]) Just as the waring says arrays to stack must be passed as a "sequence" type such as list or tuple So pass them as a list. Commented Dec 7, 2021 at 19:55

1 Answer 1

1

Expanding on the comment.

If I define a simple function:

def foo(x):
    return x

and call it as you did vstack:

In [53]: foo(x[:,0] for x in np.ones((2,3,3)))
Out[53]: <generator object <genexpr> at 0x7fc5d961bc10>

The for expression created a generator. We have to wrap it in list to get an actual list:

In [54]: list(_)
Out[54]: [array([1., 1., 1.]), array([1., 1., 1.])]

Adding [] to your expression creates the list:

In [55]: foo([x[:,0] for x in np.ones((2,3,3))])
Out[55]: [array([1., 1., 1.]), array([1., 1., 1.])]

Other syntax for making a generator versus a list:

In [56]: (x[:,0] for x in np.ones((2,3,3)))
Out[56]: <generator object <genexpr> at 0x7fc5d02a1190>
In [57]: [x[:,0] for x in np.ones((2,3,3))]
Out[57]: [array([1., 1., 1.]), array([1., 1., 1.])]

Code for functions like vstack was written in way that works with generators, but developers are working to clean up details like this, making things more consistent.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.