Home > OS >  List of lists: looping to convert strings to floats
List of lists: looping to convert strings to floats

Time:03-26

I have a data object of the type: list[lists['string', 'string', floats]], but actually the floats are strings too, which I want to convert to floats. I tried the following but for some reason it still loops over the first two elements in the internal lists, but the if statement seems correct? Does anyone know what I'm doing wrong?

list_of_lists = [
    ['bla1', 'bla2', '1.', '2.', '3.', '4.'],
    ['bla3', 'bla4', '5.', '6.', '7.', '8.']
    ]

for idx_datapoint, datapoint in enumerate(list_of_lists):
    print(f'{datapoint = }')
    for idx_feature, feature_val in enumerate(datapoint):
        if idx_feature in (0, 1):
            print(f'{idx_feature = }, {feature_val = }')
            print(f'{float(feature_val) = }')
            list_of_lists[idx_datapoint][idx_feature] = float(feature_val)

Thank you for your help in advance!! I think I'm overlooking something small, so sorry in advance :D

CodePudding user response:

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).

CodePudding user response:

A simple try block might do the trick:

list1 = ['hello', '1.3', 1, 2, 3]
list2 = []
# print(list1[0].isfloat())
for i in list1:
    try:
        list2.append(float(i))
    except ValueError:
        list2.append(i)
print(list2)

Output:

['hello', 1.3, 1.0, 2.0, 3.0]

CodePudding user response:

Your missing a not after the if statement, because you don't want the first two elements from your datapoint. You should do:

if not idx_feature in (0, 1):

CodePudding user response:

I'd say:

"""
Checks if argument is floatable
"""
def is_float(element: any) -> bool:
    try:
        float(element)
        return True
    except ValueError:
        return False

"""
iterates over the list of lists
"""
for lst in list_of_lists:
 list_of_lists  = [l if not is_float(l) else float(l) for l in lst]
  • Related