0

Assume I have a list of strings and I want to convert it to the numpy array. For example I have

A=A=['[1 2 3 4 5 6 7]','[8 9 10 11 12 13 14]']
print(A)
['[1 2 3 4 5 6 7]', '[8 9 10 11 12 13 14]']

I want my output to be like the following : a matrix of 2 by 7

[1 2 3 4 5 6 7;8 9 10 11 12 13 14]

What I have tried thus far is the following:

m=len(A)
M=[]
for ii in range(m):
    temp=A[ii]
    temp=temp.strip('[')
    temp=temp.strip(']')
    M.append(temp)
print(np.asarray(M))

however my output is the following:

['1 2 3 4 5 6 7' '8 9 10 11 12 13 14']

Can anyone help me to correctly remove the left and right brackets and convert the result to the matrix of floats.

3
  • Where did your strings come from? Commented Jun 18, 2019 at 5:07
  • Look at stackoverflow.com/q/56627106/901925 Commented Jun 18, 2019 at 5:09
  • @StephenRauch from reading a csv file in python using panda Commented Jun 18, 2019 at 5:15

1 Answer 1

1

Just go the direct route. Remove the brackets, split on the spaces and convert to float before sending the result to numpy.array:

np.array([[float(i) for i in j[1:-1].split()] for j in A])

Test Code:

import numpy as np
A = ['[1 2 3 4 5 6 7]','[8 9 10 11 12 13 14]']
print(np.array([[float(i) for i in j[1:-1].split()] for j in A]))

Results:

[[  1.   2.   3.   4.   5.   6.   7.]
 [  8.   9.  10.  11.  12.  13.  14.]]
Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain what your code does ? what would be the unwrapped version of your code?
I did explain. Remove the brackets, split on the spaces and convert to float. Other than that, go study list comprehensions
@user59419, I think it would be a good Python exercise for you to translate the list comprehension to a loop (two loops actually). There's a straight forward mapping between append loops as you started with and list comprehensions.

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.