0

I have a string like that:

'[[-1. ]
 [ 4.5]
 [ 0. ]]

[[ 8.]
 [ 0.]
 [ 6.]]

[[ 0.        ]
 [ 4.        ]
 [ 0.66666667]]'

and I want to convert into a NumPy array like this

array([[[-1.        ],
        [ 4.5       ],
        [ 0.        ]],

       [[ 8.        ],
        [ 0.        ],
        [ 6.        ]],

       [[ 0.        ],
        [ 4.        ],
        [ 0.66666667]]])

i try this code but didn't gat my answer

np.array(list(string.replace(']','],')))
2
  • 1
    For your firsts steps I will do something like: # Remove all white spaces while string.find(" ") != -1: string = string.replace(" ", "") # Add comma between brackets string = string.replace("][", "],[") Then you will need to convert it into a list object where each element is a string you can convert into an int. Commented Dec 3, 2020 at 11:39
  • Does this answer your question? Convert 4D array of floats from txt (string) file to numpy array of floats Commented Dec 3, 2020 at 11:59

1 Answer 1

1

If you know the size before hand then

np.fromstring(
    s.replace('[', '').replace(']','').replace('\n', ''), 
                dtype=float, sep=' ').reshape(3,3)

Testcase:

s = '''[[-1. ]
 [ 4.5]
 [ 0. ]]

[[ 8.]
 [ 0.]
 [ 6.]]

[[ 0.        ]
 [ 4.        ]
 [ 0.66666667]]'''

np.fromstring(
    s.replace('[', '').replace(']','').replace('\n', ''), 
                dtype=float, sep=' ').reshape(3,3)

Output:

array([[-1.        ,  4.5       ,  0.        ],
       [ 8.        ,  0.        ,  6.        ],
       [ 0.        ,  4.        ,  0.66666667]])
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.