Convert a array with float numbers and string numbers to float - python

I have a string with float numbers where decimal separator is dot like 1.2, 4.2 and so on. And also other numbers where the decimal separator is comma like 2,5, 8,3 and so on. I would like to convert everything to float numbers with dot as decimal separator. I am trying with the following code
df["numbers"].apply(lambda x: x if x.is_float() else x.replace(',','.'))
When excecuting that line I receive a message that says: 'str' object has no attribute 'is_float'
Can anyone help me?
Thanks

Python strings have no attribute is_floatIf you want python to detect whether a string is a float, you can use str.isdecimal().
Note: You don't need that if statement. If the string doesn't contain a ',', calling str.replace(',','.') will not trigger an error, it will just leave it as it is.

Convert x to float after replacing, so that it always is a float number instead of a string, try:
df["numbers"].apply(lambda x: x if x.is_float() else float(x.replace(',','.')))

Related

In Python, how can I get a whole number without decimals from math.sqrt?

import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).

Convert float to string without losing information - Python

I am trying to use geopy to reverse fetch location deatils based off of location coordinates. Right now I have Lat and Long in two different columns in pandas and both are of float type. Now to use locator.reverse(''), the input must be a string. And when I try to cast float to string, I am losing some information in the form of changed numbers like
df.Lat[0] = 42.279971
df.Lat.astype('str')
df.Lat[0] = 42.27997063
Why is it rounding off? I need exactly the float number as it is given to me?
Thanks for helping!
In your case here, you are not losing precision by converting float to string. Instead, it is because Pandas defaults to show only 6 decimal points for float numbers. When you convert it to string, this output default is not applied.
You can test it by e.g. to set the default float precision to 8:
pd.set_option("precision", 8)
Then, you will see that before the string conversion, the values is already in that precision already.
I am not sure it can help or not, it convert all cells in dataframe into string
df = df.applymap(lambda x: str(x))
Use repr() to convert float to string without losing precision:
Try:
df.Lat = df.Lat.apply(lambda x: repr(x))
Or
df.Lat = df.Lat.apply(repr)

How to convert from float to int to string? invalid literal for int() with base 10: 'x'

how convert float to int to string?
with open(DATA_DIR+'/test.csv', 'r') as inp:
reader = csv.DictReader(inp, delimiter=',',fieldnames = ['Id', 'Target'])
for row in csv.reader(inp):
text_file.write("Text "+str(int(row[1])))
Error: ValueError: invalid literal for int() with base 10: '323.0'
EDIT: The CSV parser is already reading the data that you are trying to convert as a string. That string has decimal point values which it won't convert to int. It will convert it to float though.
Here are 2 ways to do this:
Just split the string and use the integral part
in your example do text_file.write('Text {:.0f}'.format(float(row[1]))
With the 2nd approach you are basically converting it to float and thereafter you don't care for anything on the right of the decimal. So .0f indicates you don't want anything after the decimal including the .. More on this formatting can be learned in the link I pasted below.
As you dig deeper you should continue to use type() to identify the incoming data before you decide what to do with it.
ORIGINAL PART:
You don't have to convert the data to achieve what you want. At the end of it you want to write to a file as a string. If what you are getting from the csv is a float then you could simply format your string as
write_line = 'Text {:06.2f}'.format(row[1])
text_file.write(write_line)
Of course you could condense the two lines.
There is more info in python's docs - https://docs.python.org/3/tutorial/inputoutput.html
x=Decimal(row[1]).normalize()
text_file.write(x)
Probably looks like row[1] is not having any numeric value. Can u specify what exactly it will hold?
Try printing row[i] before executing the int() function and see what value it is holding.

Python - Converting String Numbers To Float

I want to convert string numbers on a list to float numbers
and i can't do it, so i need some help.
num = '0.00003533'
print('{:f}'.format(float(num)))
formatting it without decimals, only returns a float of 0.000035, i need the entire string in a float.
print('{:8f}'.format(float(num)))
adding the exact decimal works, but the numbers in the list with decimals varies greatly, so i can't manually add it everytime, how could i automatically add the correct decimal number inside the format?
something like '{':exactdecimalf'} exactdecinal being a variable.
i'm using a module that requires float, which is why i can't print it directly from the string format.
Use this
from decimal import Decimal
num = '0.00003533'
print(Decimal(num)) #0.00003533
if you want to print as string
print ('{:f}'.format(Decimal(num)))
Maybe double precision will suit you.
from decimal import Decimal
print ('{:f}'.format(Decimal(num)))
You can split the string and take the length of the last part with
len(num.split(".")[1])
Then use that as the number of decimals.

How to convert exponential value to string format in python?

I'm doing some calculations which give very small decimal numbers for example, 0.0000082
When I'm saving it in a variable, it changes into exponent form. I need the result as a string in the end. So, converting the result using str() is not possible because it keeps the e in the string.
I need the string to have exactly 8 decimal places. Is there any way to do this while keeping the 8 digit precision intact?
Another example: 5.8e-06 should be converted to '0.00000580' The trailing zero in the final string is not important.
I need the string to be used elsewhere. So, this shouldn't be done in the print() function.
The exponential notation is not an inherent property of the number (which is stored as a binary floating point value). It's just the default representation when converting the number to a string with str. You can specify your own formatting options if you convert the number to a string using the format function. Try something like this:
format(5.8e-06, '.8f')
The 8 in the format specifier tells it to use eight digits of precision, while the f requests it to be written as a plain decimal without exponential notation. You can read more about the format notations in the documentation.
Just another idea:
'{0:.7f}'.format(0.0000082)
you can try with :
import decimal
print(str(decimal.Decimal(5.8e-06))[:10])
>>> 0.00000580
print ("{:.6f}".format(1e-4))
will print out
0.000100
You could use print:
>>> number = 1e-08
>>> number
1e-08
>>>print("{:.12f}".format(float(number)))
0.000000010000
or You could convert number and store it in string:
>>> str1 = "{:.12f}".format(float(number))
>>> str1
'0.000000010000'

Categories

Resources