1

Say I have a list of lists with similar elements like

    [['string', 'string', 'number', 'number', 'number'], ['string', 'string', 'number', 'number', 'number']]

How would I go about converting just the numbers to float? Thanks for any help.

Edit:
So I have a csv file that has data formatted this way. I extracted the data by putting the lines as a list of lists. When I eventually print the data as a formatted table, I want the numbers to be formatted as rounded floats.

Skyler Dyer
  • 13
  • 1
  • 4
  • Is the conversion done in place? Is it extracting the numbers to a new list? – zglin Apr 04 '17 at 03:13
  • How does your desired output look like? What float number do you want for `'number'`, because `float('number')` doesn't make any sense. Please edit the question to provide more information. – Sangbok Lee Apr 04 '17 at 03:14
  • Ok, I added more info, hopefully that helps. Let me know if even more detail is needed. Thanks. – Skyler Dyer Apr 04 '17 at 03:19

3 Answers3

2
import numpy as np
f= [['1', '5', '8', '2', '7'], ['5', '8', '3', '7', '6']]
f=np.array(f,float)

Output

[[1,5,8,2,7][5,8,3,7,6]]
Raj Shah
  • 21
  • 2
  • 2
    Please edit your post to explain what you have changed, not just the code and the end result. We aren't spoonfeeding here, you should explain to the asker what has changed and why it works, what was the original error and why is it significant? See [how to answer](https://stackoverflow.com/help/how-to-answer) on the help pages. – Jacob Birkett Feb 17 '18 at 06:57
0

You'll want to traverse the list with a custom function like this one

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

This will ensure no matter how nested your list you can iterate over all the items

f=[['string', 'string', '4', '5', '6'], ['string', 'string', '7', '8', '9']]
print(list(traverse(f)))
['string', 'string', '4', '5', '6', 'string', 'string', '7', '8', '9']

Next you'll want to use a list comprehension with a function like is_number

def is_number(s):
    try:
        float(s)
        return float(s)
    except ValueError:
        return s
    

This will allow you to navigate through the array and convert only the numbers to acutal numbers

f=[is_number(x) for x in list(traverse(f))]
['string', 'string', 4.0, 5.0, 6.0, 'string', 'string', 7.0, 8.0, 9.0]
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
zglin
  • 2,891
  • 2
  • 15
  • 26
0

Assuming all elements are string.

a = ['a', '9.99']
[float(x) for x in a if not x.isalpha()]
# [9.99]

If input is a nested list, you can first flatten it like this.

Community
  • 1
  • 1
Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33