1

I am trying to split this element:

'(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'

to a numpy array. I tried the following:

'(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'.split(', ')

but then I have the following:

['(353.0206847485174',
 '351.209306627799',
 '357.05459767397815',
 '351.53131418867196',
 '350.8487161820783',
 '356.76859139989006)']

So the first and last element still has the columns, any idea how to fix that? thanks

Viktor.w
  • 1,787
  • 2
  • 20
  • 46

2 Answers2

3

I assume you really want an array of numbers, not an array of strings.

>>>import ast
>>>import numpy as np
>>>s = '(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'
>>> np.array(ast.literal_eval(s))
array([353.02068475, 351.20930663, 357.05459767, 351.53131419,
       350.84871618, 356.7685914 ])
>>>
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
1

You can do it without any additional dependencies

s = '(353.0206847485174, 351.209306627799, 357.05459767397815, 351.53131418867196, 350.8487161820783, 356.76859139989006)'
nums = s.strip('(').strip(')').split(',')
numbers = [float(n.strip()) for n in nums]

This gives you the values as a list and if you want it as a numpy array replace the last line with

import numpy as np
numbers = np.array([float(n.strip()) for n in nums])