0

I have the list of data:

rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']

I need to convert it into float in order to calculate the average and etc.

I've tried:

list(map(float, rfd_per_neihborhood_15))

list(np.float_(rfd_per_neihborhood_15))
for item in list:
    float(item)
a = rfd_per_neihborhood_15
floats = []
for element in a:
    floats.append(float(element))
print(floats)

Nothing is working, it's throwing ValueError: could not convert string to float: '-'

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Does this answer your question? [In Python, how do I convert all of the items in a list to floats?](https://stackoverflow.com/questions/1614236/in-python-how-do-i-convert-all-of-the-items-in-a-list-to-floats) – Tomerikoo May 11 '21 at 12:32

2 Answers2

0

The problem could be that there is an element in your list which has a - (hyphen). To tackle that, you can use try-except in the following manner:

rfd_per_neihborhood_15 = ['75.8','108.5','76.6','96.4','104.8','95.8','165.8','128.9','4-4']

def safe_float(x):
    try:
        return float(x)
    except:
        print(f"Cannot convert {x}")
        #Returning a 0 in case of an error. You can change this based on your usecase
        return 0
list(map(safe_float, rfd_per_neihborhood_15))

Output:

Cannot convert 4-4
[75.8, 108.5, 76.6, 96.4, 104.8, 95.8, 165.8, 128.9, 0]

As you can see, my code gracefully handled the exception and returned a 0 in place of the last element '4-4'. Alternatively, you could also return a NaN.

paradocslover
  • 2,932
  • 3
  • 18
  • 44
  • 1
    you were right, I thought that problem with the code, but I had one data with no value. Thank you very much, I will pay more attention to my data source before working with it – Yuliya Hilevich May 11 '21 at 13:02
0

You could try this:

rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']

# shortening the name to r_pn15
r_pn15 = rfd_per_neihborhood_15

floated_list = []
for item in r_pn15:
    r_pn15.append(float(item))

print(floated_list)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61