rwolst
rwolst

Reputation: 13682

Convert Python list of strings into floats, where list also contains words

Consider for example the list in Python containing both strings of letters and numbers

a = ['Total', '1', '4', '5', '2']

How would it be possible to convert this into the mixed value list

b = ['Total', 1.0, 4.0, 5.0, 2.0]

Note that in general we may not know where the letters string will be in the list i.e. we might have

a = ['Total', '1', '4', 'Next', '2']

Upvotes: 2

Views: 6263

Answers (3)

U2EF1
U2EF1

Reputation: 13279

Assuming your end goal isn't a csv package, I'd recommend pandas.read_csv.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

You can use a generator function and exception handling:

>>> def func(seq):
        for x in seq:
            try:
                yield float(x)
            except ValueError:
                yield x
...             
>>> a = ['Total', '1', '4', '5', '2']
>>> list(func(a))
['Total', 1.0, 4.0, 5.0, 2.0]

Upvotes: 5

Martijn Pieters
Martijn Pieters

Reputation: 1123540

Just convert everything but the first column:

b = a[:1] + [float(i) for i in a[1:]]

Judging from your other question you are processing a CSV file, so if the first column is always a string there is no point in converting that part of each row:

>>> a = ['Total', '1', '4', '5', '2']
>>> a[:1] + [float(i) for i in a[1:]]
['Total', 1.0, 4.0, 5.0, 2.0]

You could also use a try: - except ValueError approach, but why incur the overhead when it is known up front what column has text and what columns have numeric values?

Upvotes: 4

Related Questions