1

I have a string which is loaded from a .mat file and is in the following format :

(array([172.169, 73.2]), array([128.83, 102.31]), array([143.49, 124.43]), array([186.83, 95.69]), 'R', array([], dtype=float64))

Is there any way I can convert this directly to a numpy 2D array without parsing over the entire string and removing the "arrays" manually? Neither numpy.fromstring nor numpy.frombuffer will work here.

4
  • If it's a string, why have you not surrounded it with quotes? Commented Apr 1, 2020 at 9:15
  • is the 'R' a typo? Commented Apr 1, 2020 at 9:16
  • @DavidBuck It's similar, but not exactly, since to convert it to a list I have to parse the string anyways. Commented Apr 1, 2020 at 9:18
  • @Back2Basics No, R is not a typo. This is an annotation file for hands. R indicates the file is for the right hand. It's not to be there in the final array, I can manually remove that Commented Apr 1, 2020 at 9:19

1 Answer 1

2

you can use np.fromstring with a regular expression:

import re

# s is your string
np.fromstring(', '.join(re.findall(r'\[(.+?)\]', s)), sep =', ').reshape((2, 2, 2))

output:

array([[[172.169,  73.2  ],
        [128.83 , 102.31 ]],

       [[143.49 , 124.43 ],
        [186.83 ,  95.69 ]]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.