RandomBits
RandomBits

Reputation: 4294

Numpy data loaded from file using memmap throws exception when used in formatted output

The following example demonstrates the issue.

>>> import numpy as np
>>> X = np.random.randn(10,3)
>>> np.save("x.npy", X)
>>> Y = np.load("x.npy", "r")
>>> Y.min()
memmap(-2.3064808987512744)

>>> print(Y.min())
-2.3064808987512744

>>> print("{}".format(Y.min()))
-2.3064808987512744

>>> print("{:6.3}".format(Y.min()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

Without the mode = 'r' in the load function, everything works as expected. Is this a bug? Or, am missing something?

Is there anyway to 'extract' the float value from the memmap to use it directly?

EDIT:

The 'item' method can be used to 'Copy an element of an array to a standard Python scalar and return it'. So, the following code works:

>>> print("{:6.3}".format(Y.min().item(0)))
  -2.31

Is there a rhyme or reason when you need to extract a value to use it?

Upvotes: 3

Views: 190

Answers (1)

hpaulj
hpaulj

Reputation: 231615

https://github.com/numpy/numpy/issues/5543

ndarray should offer format that can adjust precision

According to this issue, from last Feb,

n = np.array([1.23, 4.56])
print('{0:.6} AU'.format(n))

produces the same error

TypeError: non-empty format string passed to object.__format__

My guess is that numpy memmap objects have the same issue, and possible the same solution.

Evidently py3 style of format is still buggy, at least for add on packages like numpy.

Upvotes: 2

Related Questions