I'm trying to use string.format on a 'nan' float.
Here's the description of the 'g' option from the python documentation.
General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. Infinity and NaN values are formatted as inf, -inf and nan, respectively.
And here's what i get trying it in the interpreter (Python 2.6):
>>> print "{0:g}".format(float('nan'))
-1.#IND
As I understand the documentation, the output should be "nan".
Is this a bug or am I doing it wrong?
In data science, Nan is used to represent the missing values in a dataset. So Nan is basically a placeholder to represent undefined or missing values. You can create the Nan value using float type. Since it is not a defined keyword in Python, you have to pass it to float in a string format (within quotes).
In Python, the float type has nan . nan stands for "not a number" and is defined by the IEEE 754 floating-point standard.
We can replace NaN values with 0 to get rid of NaN values. This is done by using fillna() function. This function will check the NaN values in the dataframe columns and fill the given value.
repr(float)
was fixed in Python 2.6 and Python 3.0; see http://bugs.python.org/issue1635; however str.format
was not fixed until the 2.7 branch; see http://hg.python.org/cpython/rev/c5e0d9beebf9 and http://bugs.python.org/issue1580.
I'd recommend seeing if "{0!r}"
works for you; that should call into the non-broken repr
code.
If you need to use "{0:g}"
format spec, you could try subclassing float
and overriding __format__
:
class FixFloat(float):
def __format__(self, format_spec):
return 'nan' if math.isnan(self) else float.__format__(self, format_spec)
"{0:g}".format(FixFloat(1.2345e9))
'1.2345e+09'
"{0:g}".format(FixFloat(float('nan')))
'nan'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With