Can one output something other than 'nan' for not a number values?

Chris Green cl at isbd.net
Mon Feb 19 07:04:44 EST 2024


dn <PythonList at danceswithmice.info> wrote:
> On 18/02/24 09:53, Grant Edwards via Python-list wrote:
> > On 2024-02-17, Cameron Simpson via Python-list <python-list at python.org> wrote:
> >> On 16Feb2024 22:12, Chris Green <cl at isbd.net> wrote:
> >>> I'm looking for a simple way to make NaN values output as something
> >>> like '-' or even just a space instead of the string 'nan'.
> >>> [...]
> >>>
> >>>     Battery Voltages and Currents
> >>>     Leisure Battery - 12.42 volts  -0.52 Amps
> >>>     Starter Battery -   nan volts    nan Amps
> >>>
> >>> What I would like is for those 'nan' strings to be just a '-' or
> >>> something similar.
> > 
> >> The simplest thing is probably just a function writing it how you want
> >> it:
> >>
> >>       def float_s(f):
> >>           if isnan(f):
> >>               return "-"
> >>           return str(f)
> >>
> >> and then use eg:
> >>
> >>       print(f'value is {float_s(value)}')
> >>
> >> or whatever fits your code.
> > 
> > Except he's obviously using some sort of formatting to control the
> > number of columns and decimal places, so 'str(f)' is not going to cut
> > it. Is the basic floating point number formatting functionality seen
> > when using f-strings or '%' operator part of the float type or is it
> > part of the f-string and % operator?
> 
> It's part of the PSL's string library: "Format Specification 
> Mini-Language" 
> https://docs.python.org/3/library/string.html#format-specification-mini-language
> 
> Has the OP stated if we're talking 'Python' or numpy, pandas, ...?
> 
Just python, on a Raspberry Pi, so currently Python 3.9.2.

-- 
Chris Green
·


More information about the Python-list mailing list