Home > Enterprise >  How to address numpy warning message about array stacking?
How to address numpy warning message about array stacking?

Time:12-08

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.

CodePudding user response:

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.

  • Related