0

I have the following array:

pattern = array([['[0, 0, 1, 0, 0]'],
       ['[0, 1, 1, 1, 1]'],
       ['[0, 1, 1, 1, 0]'],
       ['[0, 0, 1, 1, 1]'],
       ['[0, 0, 0, 1, 1]'],
       ['[0, 0, 1, 0, 1]'],
       ['[0, 0, 0, 0, 1]'],
       ['[1, 0, 1, 0, 0]'],
       ['[0, 1, 0, 1, 1]'],
       ['[0, 0, 1, 1, 0]'],
       ['[1, 1, 1, 1, 1]'],
       ['[1, 1, 1, 1, 0]']], dtype='<U15')

and I want to get it in non-string format as the following:

import numpy
my_array = numpy.array([[0, 0, 1, 0, 0],
                        [0, 1, 1, 1, 1],
                        [0, 1, 1, 1, 0],
                        [0, 0, 1, 1, 1],
                        [0, 0, 0, 1, 1],
                        [0, 0, 1, 0, 1],
                        [0, 0, 0, 0, 1],
                        [1, 0, 1, 0, 0],
                        [0, 1, 0, 1, 1],
                        [0, 0, 1, 1, 0],
                        [1, 1, 1, 1, 1],
                        [1, 1, 1, 1, 0]
                        ])

Any idea on how to do it non-manually?

1
  • 1
    Sure, list comprehension makes tasks like this pretty trivial, but what have you tried yourself already? Commented Dec 20, 2022 at 17:22

1 Answer 1

1

Using numpy string operations to strip brackets ([]), splitting on comma and recast into an array with int dtype is possible:

np.array(np.char.split(np.char.strip(pattern[:, 0], '[]'), ', ').tolist(), 'int')

but a list comprehension where you do the same things using python string methods is much easier to read (and faster as well) imo.

np.array([row[0][1:-1].split(', ') for row in pattern], dtype='int')


# array([[0, 0, 1, 0, 0],
#        [0, 1, 1, 1, 1],
#        [0, 1, 1, 1, 0],
#        [0, 0, 1, 1, 1],
#        [0, 0, 0, 1, 1],
#        [0, 0, 1, 0, 1],
#        [0, 0, 0, 0, 1],
#        [1, 0, 1, 0, 0],
#        [0, 1, 0, 1, 1],
#        [0, 0, 1, 1, 0],
#        [1, 1, 1, 1, 1],
#        [1, 1, 1, 1, 0]])
Sign up to request clarification or add additional context in comments.

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.