Python turning 2 dimensional strings on my list into floats
Your read_points()
is returning a value that is a blank string that the float
cannot do anything with.
If I do read_points()
and enter '5','4','3'
this is returned [['5'], ['4'], ['3'], ['']]
The last item in that list throws the error when float('')
is attempted. So either you need to fix it in read_points()
to only return the inputted and not blank line, or deal with non-integers in the 2nd function.
So an alternate to your code could like:
def read_points():
print("Input the points, one per line as x,y.")
print("Stop by entering an empty line.")
arvo = 0
pointslist = []
while arvo != "":
arvo = input("")
kordinaatti = arvo.split(",")
pointslist.append(kordinaatti)
return pointslist[:-1]
def calculate_midpoint(pointslist):
h = len(pointslist)-1
j = int(0)
summax = 0
summay = 0
while j <= h:
arvox = pointslist[j][0]
arvoy = pointslist[j][0]
summax += float(arvox)
summay += float(arvoy)
summax = float(summax / h)
summay = float(summay / h)
j += 1
return summax, summay
Convert Multidimensional array string to float in python
You can use np.ndarray.astype()
function -
Example -
In [5]: n= np.array([['120', '29.9475077984', '1'],
...: ['125', '31.3887667742', '1'],
...: ['125', '32.3881706091', '1'],
...: ['125', '34.4894481007', '1'],
...: ['126', '36.1494551046', '1'],
...: ['127', '39.3121447948', '1'],
...: ['128', '43.8203811171', '1'],
...: ['128', '49.3179066095', '1'],
...: ['128', '53.4929489926', '1'],
...: ['128', '55.1837748899', '1'],
...: ['130', '55.9167038553', '1'],
...: ['130', '56.2727376481', '1'],
...: ['130', '57.480058071', '1'],
...: ['130', '60.3922465138', '1'],
...: ['130', '61.2506277637', '1'],
...: ['130', '60.5279054759', '1'],
...: ['143', '62.139526711', '1'],
...: ['143', '65.4147315349', '1'],
...: ['143', '72.3278873965', '1']])
In [8]: n = n.astype(np.float)
In [9]: n
Out[9]:
array([[ 120. , 29.9475078 , 1. ],
[ 125. , 31.38876677, 1. ],
[ 125. , 32.38817061, 1. ],
[ 125. , 34.4894481 , 1. ],
[ 126. , 36.1494551 , 1. ],
[ 127. , 39.31214479, 1. ],
[ 128. , 43.82038112, 1. ],
[ 128. , 49.31790661, 1. ],
[ 128. , 53.49294899, 1. ],
[ 128. , 55.18377489, 1. ],
[ 130. , 55.91670386, 1. ],
[ 130. , 56.27273765, 1. ],
[ 130. , 57.48005807, 1. ],
[ 130. , 60.39224651, 1. ],
[ 130. , 61.25062776, 1. ],
[ 130. , 60.52790548, 1. ],
[ 143. , 62.13952671, 1. ],
[ 143. , 65.41473153, 1. ],
[ 143. , 72.3278874 , 1. ]])
How to convert string list into float list
list(map(float, word.split(':')))
This will convert each of the number to float
Convert 2-d array of strings to float in python_removing scientific notation
You're intrinsically limited by the fact that floating point numbers are stored using IEEE 754. You can't have arbitrary precision floating points, so in your case, you can't expect them to necessarily be exactly the same as a string representation.
However, in your case, the more pressing issue is that want to compare a string to a float, so of course they are going to be different. Python is dynamically, but strongly typed.
Given both the above points, you need to better define your problem. Why do you need to compare with an array of strings? (what does this even mean!?)
Can you test for closeness rather than equality once you have your data types sorted out (e.g. using numpy.close
)?
How to convert a 2D array of strings and numbers to a numpy float array?
Using genfromtext
as suggested here is not possible with multi-dimensional arrays. On the other hand, you can apply genfromtext
to each row of the 2D array using apply_along_axis
as described here:
import numpy as np
x = np.array([[1, 2, 'tom'], [4, 'Manu', 6]])
print(np.apply_along_axis(np.genfromtxt, 1 ,x))
Which will give:
[[ 1. 2. nan]
[ 4. nan 6.]]
List of lists: looping to convert strings to floats
Keep in mind that some of the values of the lists have letters in them, so they cant be changed into floats. Other than that, this is how I would do it:
list_of_lists = [
['bla1', 'bla2', '1.', '2.', '3.', '4.'],
['bla3', 'bla4', '5.', '6.', '7.', '8.']
]
for i, list in enumerate(list_of_lists):
for i2, v in enumerate(list):
try:
list_of_lists[i][i2] = float(v)
except ValueError:
pass # change to whatever you want to do if you cant change it
I just tested it and it seems to work fine. Just change the 'pass' line to whatever you want to do with the values that have letters in them (like removing them or removing the letters).
Related Topics
How to Get the Name of an Object
How to Convert Signed to Unsigned Integer in Python
Convert HTML String to an Image in Python
Changing Presence Discord Status
Cannot Convert the Series to <Class 'Int''>
Read CSV from Google Cloud Storage to Pandas Dataframe
Python | Make the Percentage of a List
How to Convert .Dat to .Csv Using Python
Hiding Raw_Input() Password Input
How to Split an Integer into an Array of Digits
Pandas Convert Columns to Percentages of the Totals
Python - How to Extract Elements from an Array Based on an Array of Indices
Scheduling Python Script to Run Every Hour Accurately
Add One Month to a Given Date (Rounded Day After) With Python
How to Truncate the Time on a Datetime Object
How to Extract the Entire Row and Columns When Condition Met in Numpy Array