1

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?

4
  • x = np.array([value for value in values], np.float) try that. Values being your strings. Commented Jun 17, 2019 at 18:13
  • Please add to the question how data_det looks like Commented Jun 17, 2019 at 18:15
  • @Raymond It is not a single list. It is list of list. Commented Jun 17, 2019 at 18:16
  • @GravityMass one second. You need to traverse a list of list then. Commented Jun 17, 2019 at 18:18

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.