## Python turning 2 dimensional strings on my list into floats

convert list to float python

numpy array of lists to 2d array

convert 2d list of strings to ints python

string to array python

convert string array to float array python

python add dimension to list

multidimensional array in python

I have a school project in which i need to make a 2 dimensional list and count the average point on that list. For some reason I can't change the values on the list into floats, even thought it prints them with print(pointslist[0][1]) into a single value.

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 def calculate_midpoint(pointslist): h = len(pointslist) j = int(0) summax = 0 summay = 0 while j <= h: arvox = pointslist[j][0] arvoy = pointslist[j][1] summax += float(arvox) summay += float(arvoy) summax = float(summax / h) summay = float(summay / h) j += 1 return summax, summay

gives error:

summax += float(arvox) ValueError: could not convert string to float: ¨

The formatting is a bit off, but its correct on the code.

Thanks for that :) Now I see the problem, but i still have the problem with this part of the code:

def calculate_midpoint(pointslist): h = len(pointslist) j = 0 summax = 0 summay = 0 while j <= h: arvox = float(pointslist[j][0]) arvoy = float(pointslist[j][1]) summax += float(arvox) summay += float(arvoy) summax = float(summax / h) summay = float(summay / h) j += 1 return summax, summay

goes out of index. The code works fine when I insert 0 for example instead of J. What value does J get, since it crashes the program?

The problem has been fixed, thanks to all of you who helped!!

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

**Python Convert String to float,** How do you convert a list of strings to a list of floats in Python? My program is supposed to read a text document with a bunch of numbers and make a list of only the positive numbers. I can't convert the strings from the text document to a float so i can't determi

Disregarding formatting issues, there are two bugs in your underlying code:

**Fencepost Issue in read_points**

`read_points`

terminates after reading an empty line, but it *also* appends this empty line to `pointslist`

, meaning that the last entry in `pointslist`

is not valid. There are many ways to fix this: a simple one is to read at the end of each iteration rather than the start:

def read_points(): print("Input the points, one per line as x,y.") print("Stop by entering an empty line.") arvo = 0 pointslist = [] arvo = input("") while arvo != "": kordinaatti = arvo.split(",") print(kordinaatti) pointslist.append(kordinaatti) arvo = input("") return pointslist

This is responsible for the "could not convert string to float" issue, since the last point is not a valid point.

**Off-by-one Issue in calculate_midpoint**

Your code iterates from `j=0`

to `j=len(pointslist)`

, and tries to access `pointslist[j]`

at each iteration. This attempts to read `len(pointslist) + 1`

items, which is incorrect; you should only read up to `j=len(pointslist) - 1`

. This is responsible for the index error you mentioned in your comment on the OP.

Fixed version:

def calculate_midpoint(pointslist): print(pointslist) h = len(pointslist) 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

How do I convert a list of elements to a string? which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy: my_list = np.array(my_list).astype(np.float) print(type(my_list), type(my_list[0])) # <class 'numpy.ndarray'> <class 'numpy.float64'>. share.

This was a good start but there are two mistakes in your code.

The first mistake was that the code that is reading the input is trying to treat the empty line as a float.

The second mistake was that the code that is calculating the mid-point is trying to process points beyond the end of the list by using `less than`

or `equal to`

in the comparison.

I have reworked your code to work correctly below.

def read_2d_points(): ''' Read 2D points from the command line. ''' print("Input the points, one per line as x,y.") print("Stop by entering an empty line.") arvo = 0 pointslist = [] while arvo != "": arvo = input("? ") if ',' in arvo: # Ignore the case where the line is empty # to avoid a float conversion error. kordinaatti = [float(x.strip()) for x in arvo.split(",")] assert len(kordinaatti) == 2 # assume 2D pointslist.append(kordinaatti) assert len(pointslist) > 1 return pointslist def calculate_midpoint(pointslist): ''' Calculate the mid point. ''' h = len(pointslist) j = int(0) summax = 0 summay = 0 while j < h: arvox = pointslist[j][0] arvoy = pointslist[j][1] summax += float(arvox) summay += float(arvoy) summax = float(summax / h) summay = float(summay / h) j += 1 return summax, summay pointsList = read_2d_points() print('points: {} {}'.format(len(pointsList), pointsList)) print('midpoint: {}'.format(calculate_midpoint(pointsList)))

If you are interested in expanding your python knowledge, i would suggest thinking about adding error handling (other than the assert), considering the use of either `classes`

or `namedtuples`

and, possibly, considering the use of list comprehensions.

Best of luck.

How do you convert a string to a float in Python? Python | Using 2D arrays/lists the right way Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.

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 str_lst=['1','2','3'] int_lst=[int(x)forxinstr_lst] print(int_lst) The output is a new list with strings converted into integers. Converting decimal list into float for list items. Similarly, you may use the floatinstead of int for converting a list containing decimal number strings. See a demonstration below:

Let's discuss a few ways to convert an array of strings to array of floats. Python code to demonstrate converting Method #2: Using np.fromstring Convert an array to an ordinary list with the same items · Python | Convert list to Python array I'm using the [Read Me] component to read a CSV file, which contains a series of decimal numbers. I'm struggling with converting the CSV data (read as strings) to floats. I've tried using [float (i) for i in x], but this calls the tree branch (i.e. {0;0;0}, etc.) as opposed to the string item. Image attached.

In this, we loop through each element and try to convert each string into float value, if it's a success, Method #2 : Using regex + list comprehension In this, we perform the task of filtering using regex created and list comprehension is used to iterate d*)' ). res = [ele for ele in test_list if not temp.match(ele)]. # printing result. To process 2-dimensional array, you typically use nested loops. The first loop iterates through the row number, the second loop runs through the elements inside of a row. For example, that's how you display two-dimensional numerical list on the screen line by line, separating the numbers with spaces: [*] step by step.

##### Comments

- What is the ¨ symbol doing in the above code? It looks like it's right after the function definition right now, which doesn't make syntactic sense.
- arvoy = pointslist[j][0] should be arvoy = pointslist[j][1]. which causes another error claiming its out of index.
- Thanks, I used if instead of the return value, but now it claims J goes out of index in the func calculate_midpoint
- Did you see the edit to calculate_midpoint? The length of the pointslist will be too long since the index starts at 0. so you need to subtract 1 or use
`while j < h`