Gravity Mass
Gravity Mass

Reputation: 605

Convert a list of list of strings into ndarray of floats

I have a list of strings like the following:

['0.20115899', '0.111678', '0.10674', '0.05564842', '-0.09271969', '-0.02292056', '-0.04057575', '0.2019901', '-0.05368654', '-0.1708179']
['-2.17182860e-01', '-1.04081273e-01', '7.75325894e-02', '7.51972795e-02', '-7.11168349e-02', '-4.75254208e-02', '-2.94160955e-02']
etc.
etc.

List's name is data_det. I did the following to find the types:

for item in data_det:
      print(type(item))
      for it in item:
           print(type(it))

I got

<class 'list'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
etc.

I tried to convert it into ndarray.

data_det = numpy.asarray(data_det, dtype=np.float)

But got the error:

return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

Ideally I want each value to be converted to float. How can this be accomplished?

Upvotes: 1

Views: 59

Answers (2)

ABC
ABC

Reputation: 2158

In regards to my comment and your comment. Since you said your data is in list of a list format. You need to traverse the list.

You use np.float to set the values incoming to a float type. Use dtype=object to set arbitrary types.

import numpy as np

# Traverse list of list
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

# Your data
values = [('0.20115899', '0.111678'), ('0.211282', '0.342342')]
# Traverse data list of list
values = traverse(values)
# Loop through new values
x = np.asarray([float(value) for value in values], np.float)
# Output
print(x)

Upvotes: 0

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Try this :

import numpy as np
l1 = ['0.20115899', '0.111678', '0.10674', '0.05564842', '-0.09271969', '-0.02292056', '-0.04057575', '0.2019901', '-0.05368654', '-0.1708179']
l2 = ['-2.17182860e-01', '-1.04081273e-01', '7.75325894e-02', '7.51972795e-02', '-7.11168349e-02', '-4.75254208e-02', '-2.94160955e-02']

l1 = np.array([float(i) for i in l1])
l2 = np.array([float(i) for i in l2])
print(l1.dtype)

Output :

float64

Upvotes: 4

Related Questions