String to Float, without introducing errors

avi.e.gross at gmail.com avi.e.gross at gmail.com
Sat Dec 17 18:05:46 EST 2022


As often seems to happen, someone asks something that may not be fully clear and others chime in and extend the question.

Was the original question how to read in a ingle column of numbers from a file that are all numeric and NOT integers and be able to use them?

If so, the answer was quite trivial using the conversion function of your choice. Handling errors or what to do with something like a blank or NA are nice ideas if asked about.

My answer would be to ask if this was an assignment where they are EXPECTED to do things a certain way to master a concept, or part of a serious attempt to get things done.

For the latter case, it may make plenty of sense considering a single column of text as just a special case for the kind of multi-column files often read in from formatted data files and use some functionality from add-on modules like numpy or pandas that also allow you to deal with many other concerns.

Note such utilities also often make a decent guess on what data type a column should be turned into and it is possible they may occasionally decide based on the data that the contents all HAPPEN to be integer or there is at least one that makes it choose character. So any such use may well require the subsequent use of functions that check the dtype and, if needed, do an explicit conversion to what you really really really want.



-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On Behalf Of Mats Wichmann
Sent: Saturday, December 17, 2022 1:42 PM
To: python-list at python.org
Subject: Re: String to Float, without introducing errors

On 12/17/22 07:15, Thomas Passin wrote:
> You have strings, and you want to end up with numbers.  The numbers 
> are not integers.  Other responders have gone directly to whether you 
> should use float or decimal as the conversion, but that is a secondary matter.
> 
> If you have integers, convert with
> 
> integer = int(number_string)
>> -64550.727

they pretty clearly aren't integers:

>> -64511.489
>> -64393.637
>> -64196.763
>> -63920.2
>> -63563.037
>> -63124.156
>> -62602.254
>> -61995.895
>> -61303.548
>> -60523.651
>> -59654.66
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list