How to convert a String to a float in Python 2.7 - string

I am trying to convert decimal geographic coordinates as strings to a float.
The coordinates are in a csv like this '51213512'. With my Python script I am just reading the coordinates and add the '.'. If I am not adding the comma the rest of my script isn't working.
I already tried a few things but nothing worked for me. This is what I got so far.
latitude=float(long('51.213512'))
The Result is a ValueError:
ValueError: invalid literal for long() with base 10: 'Long'

not too sure why you are using long in this examply if you want to convert this variable to a float just use the float function on its own, you seem to be confusing the long and float functions. dont use both you will be confusing python (basically dosent know what to do because your giving it 2 arguments at once)
I recommend just using the float function on its own. This will avoid confusion
latitude = float('51.2135512')

Get rid of the 'long' and it should work
latitude = float('51.213512')
Edit: Okay, since you're getting the coordinates and manually converting to decimal strings, all you need to do is use the code I said originally. The long function
converts integers or strings of integers to long types, not float types.
>>> long(5)
5L
>>> long('5')
5L
>>> long(5.5)
5L
>>> long('5.5')
ValueError: invalid literal for long() with base 10: '5.5'

Related

ValueError: could not convert string to float: '[-0.32062087,0.27050002,......]'

My dataframe has columns where one has list of float values. When I train that column as X_train, I showing cannot string to float or tensorflow float data type.
DataSet:
I tried this:
df['sent_to_vec'].apply(lambda x: float(x))
or nested for loop to convert values in float type; but didn't get executed.
Try passing a string that's really just a floating-point number to the Python float() function:
f1 = float('0.1')
print(f1)
It works.
Try passing a string that's not just a floating-point number, but is instead some sort of array or list representation with multiple numbers separated by other punctuation:
f2 = float('[0.1, 0.2]')
print(f2)
You'll get the same error as you're asking about. That string, '[0.1, 0.2]' is not a representation of a floating-point number that float() can read.
You should look for a function that can read a string like '[0.1, 0.2]'. Can you see the code that wrote the Vectorized data.csv file? (Did you write that code, or that file?)
You'll want to use some function that does the reverse of whatever wrote that column of the file.

why is my int() conversion looking so weird?

I'm trying to take a number and divide it by 100 to get 1%, but when i tried to convert it to integer using the int(), it's giving me some weird output. i have no clue what i'm doing wrong here.
totalsupply = 1000000000000000000000000000000
onepercent = int((totalsupply/100))
print(totalsupply)
print(onepercent)
the output is coming out as such:
1000000000000000000000000000000
9999999999999999583119736832
[Finished in 68ms]
I was expecting the onepercent to be this: 10000000000000000000000000000.
According to this post, python tries to convert the number to a float on a division. However, floats are limited to 1.7976931348623157e+308. A workaround is to use the // operator which returns an int from the division, so for your example:
totalsupply = 1000000000000000000000000000000
onepercent = totalsupply//100
print(totalsupply)
print(onepercent)
Python has a built-in integer type that has infinite precision. That's what you are creating with your first line
totalsupply = 1000000000000000000000000000000
However, python has two division operators. The standard division "slash" operator ("/") is floating-point operation, whereas the double-slash gives integers.
Hence totalsupply/100 is a floating point number, which has finite precision, and so the closest it can do is 9999999999999999583119736832.
However, if instead you do
onepercent = totalsupply//100
print(onepercent)
you get the expected 100000000000000000000000000000.

Float to Binary and Binary to Float in Python

Can anyone tell me how to convert a float number to 32-bit binary string and from a 32-bit binary string to a float number in python?
'bin' function in python works only for integers.
I need a single bit string as in internal representation. I do not want separate bit strings for the number before and after the decimal places joined by a decimal place in between.
EDIT: The question flagged does not explain how to convert binary string to float back.
Copied from this answer and edited per suggestion from Mark Dickinson:
import struct
def float_to_bin(num):
return format(struct.unpack('!I', struct.pack('!f', num))[0], '032b')
def bin_to_float(binary):
return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]
print float_to_bin(3.14) yields “01000000010010001111010111000011”.
print bin_to_float("11000000001011010111000010100100") yields “-2.71000003815”.
I was able to create a program that takes bin decimals as string an returns int decimals!
I used a for loop to start from 1 until the len() of the str+1 to use i number to elevate 2 and, then just keep track of the result with result +=:
def binary_poin_to_number(bin1)->float:
#Try out string slicing here, later
result = 0
for i in range(1,len(bin1)+1):
if bin1[i-1] == '1':
result += 2**-i
return result

Hexadecimal string with float number to float

Iam working in python 3.6
I receive from serial comunication an string '3F8E353F'. This is a float number 1.111. How can I convert this string to a float number?
Thank you
Ah yes. Since this is 32-bits, unpack it into an int first then:
x='3F8E353F'
struct.unpack('f',struct.pack('i',int(x,16)))
On my system this gives:
>>> x='3F8E353F'
>>> struct.unpack('f',struct.pack('i',int(x,16)))
(1.1109999418258667,)
>>>
Very close to the expected value. However, this can give 'backwards' results based on the 'endianness' of bytes in your system. Some systems store their bytes least significant byte first, others most significant byte first. See this reference page for the descriptors to format based on byte order.
I used struct.unpack('f',struct.pack('i',int(x,16))) to convert Hex value to float but for negative value I am getting below error
struct.error: argument out of range
To resolve this I used below code which converts Hex (0xc395aa3d) to float value (-299.33). It works for both positive as well for negative value.
x = 0xc395aa3d
struct.unpack('f', struct.pack('I', int(x,16) ))
Another way is to use bytes.fromhex()
import struct
hexstring = '3F8E353F'
struct.unpack('!f', bytes.fromhex(hexstring))[0]
#answer:1.1109999418258667
Note: The form '!' is available for those poor souls who claim they can’t remember whether network byte order is big-endian or little-endian (from struct docs).

How to convert numpy bytes to float in python3?

My question is similar to this; I tried using genfromtxt but still, it doesn't work. Reads the file as expected but not as floats. Code and File excerpt below
temp = np.genfromtxt('PFRP_12.csv', names=True, skip_header=1, comments="#", delimiter=",", dtype=None)
reads as (b'"0"', b'"0.2241135"', b'"0"', b'"0.01245075"', b'"0"', b'"0"')
"1 _ 1",,,,,
"Time","Force","Stroke","Stress","Strain","Disp."
#"sec","N","mm","MPa","%","mm"
"0","0.2241135","0","0.01245075","0","0"
"0.1","0.2304713","0.0016","0.01280396","0.001066667","0.0016"
"0.2","1.707077","0.004675","0.09483761","0.003116667","0.004675"
I tried with different dtypes (none, str, float, byte), still no success. Thanks!
Edit: As Evert mentioned I tried float also but reads all them as none (nan, nan, nan, nan, nan, nan)
Another solution is to use the converters argument:
np.genfromtxt('inp.txt', names=True, skip_header=1, comments="#",
delimiter=",", dtype=None,
converters=dict((i, lambda s: float(s.decode().strip('"'))) for i in range(6)))
(you'll need to specify a converter for each column).
Side remark Oddly enough, while dtype="U12" or similar should actually produce strings instead of bytes (avoiding the .decode() part), this doesn't seem to work, and results in empty entries.
Here is a fancy, unreadable, functional programming style way of converting your input to the record array you're looking for:
>>> np.core.records.fromarrays(np.asarray([float(y.decode().strip('"')) for x in temp for y in x]).reshape(-1, temp.shape[0]), names=temp.dtype.names, formats=['f'] * len(temp.dtype.names))
or spread out across a few lines:
>>> np.core.records.fromarrays(
... np.asarray(
... [float(y.decode().strip('"')) for x in temp for y in x]
... ).reshape(-1, temp.shape[0]),
... names=temp.dtype.names,
... formats=['f'] * len(temp.dtype.names))
I wouldn't recommend this solution, but sometimes it's fun to hack something like this together.
The issue with your data is a bit more complicated than it may seem.
That is because the numbers in your CSV files really are not numbers: they are explicitly strings, as they have surrounding double quotes.
So, there are 3 steps involved in the conversion to float:
- decode the bytes to Python 3 (unicode) string
- remove (strip) the double quotes from each end of each string
- convert the remaining string to float
This happens inside the double list comprehension, on line 3. It's a double list comprehension, since a rec-array is essentially 2D.
The resulting list, however is 1D. I turn it back into a numpy array (np.asarray) so I can easily reshape to something 2D. That (now plain float) array is then given to np.core.records.fromarrays, with the names taken from the original rec-array, and the formats set for each field to float.

Resources