[Numpy-discussion] numpy scalars and savez -- bug?

Robert Kern robert.kern@gmail....
Thu Apr 18 06:04:48 CDT 2013


On Thu, Apr 18, 2013 at 5:58 AM, Chris Barker - NOAA Federal
<chris.barker@noaa.gov> wrote:
> Folks,
>
> I've discovered somethign intertesting (bug?) with numpy scalars ans
> savz. If I save a numpy scalar, then reload it, ot comes back as
> rank-0 array -- similar, but not the same thing:
>
> In [144]: single_value, type(single_value)
> Out[144]: (2.0, numpy.float32)
>
> In [145]: np.savez('test.npz', single_value=single_value)
>
> In [146]: single_value2 = np.load('test.npz')['single_value']
>
> In [147]: single_value, type(single_value)
> Out[147]: (2.0, numpy.float32)
>
> In [148]: single_value2, type(single_value2)
> Out[148]: (array(2.0, dtype=float32), numpy.ndarray)
>
> straight np.save has the same issue (which makes sense, I'm sure savez
> uses the save code under the hood):
>
> In [149]: single_value, type(single_value)
> Out[149]: (2.0, numpy.float32)
>
> In [150]: np.save('test.npy', single_value)
>
> In [151]: single_value2 = np.load('test.npy')
>
> In [152]: single_value2, type(single_value2)
> Out[152]: (array(2.0, dtype=float32), numpy.ndarray)
>
>
> This has been annoying, particular as rank-zero scalars are kind of a pain.

np.save() and company (and the NPY format itself) are for arrays, not
for scalars. np.save() uses an np.asanyarray() to coerce its input
which is why your scalar gets converted to a rank-zero array.

--
Robert Kern


More information about the NumPy-Discussion mailing list