Hướng dẫn convert to float python
I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a list. So I have this list:
How do I convert each of the values in the list from a string to a float? I have tried:
But this doesn't seem to work for me.
Wenuka 7312 gold badges8 silver badges20 bronze badges asked Oct 23, 2009 at 15:33 2
to be precise, it creates a new list
with float values. Unlike the answered Oct 23, 2009 at 15:34
SilentGhostSilentGhost 293k64 gold badges301 silver badges291 bronze badges 4
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need answered Oct 23, 2009 at 15:34
Tim PietzckerTim Pietzcker 318k56 gold badges492 silver badges548 bronze badges 1
This would be an other method (without using any loop!):
answered May 26, 2018 at 12:35
Amin KianyAmin Kiany 6436 silver badges16 bronze badges 1
The same code can written shorter using list comprehension: To change list in-place:
BTW, avoid using answered Oct 23, 2009 at 15:44
Denis OtkidachDenis Otkidach 30.9k8 gold badges75 silver badges97 bronze badges 2 you can even do this by numpy
this return np array of your list as float you also can set 'dtype' as int answered Sep 16, 2018 at 12:37
AlirezaAlireza 7267 silver badges10 bronze badges 1 You can use the
answered May 23, 2021 at 4:44
mnaghd01mnaghd01 1052 silver badges6 bronze badges You can use numpy to convert a list directly to a floating array or matrix.
If you want to convert the integer array to a floating array then add 0. to it
answered Jan 7, 2016 at 15:13
bfree67bfree67 5896 silver badges5 bronze badges you can use numpy to avoid looping:
answered Jul 9, 2020 at 0:48
1 This is how I would do it.
Stephen Rauch♦ 45.6k30 gold badges105 silver badges126 bronze badges answered Jan 27, 2018 at 23:41
SamlexSamlex 1191 silver badge5 bronze badges
which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:
answered May 16, 2018 at 12:33
I had to extract numbers first from a list of float strings:
then each convert to a float:
in the end assign all floats to a dataframe as float64:
answered Mar 5, 2019 at 13:34
Max KleinerMax Kleiner 1,16211 silver badges13 bronze badges I have solve this problem in my program using:
sentence 7,3974 gold badges31 silver badges37 bronze badges answered Sep 4, 2018 at 13:53
1
double-beep 4,57613 gold badges30 silver badges40 bronze badges answered May 23, 2019 at 16:05
|