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.

user59419
  • 893
  • 8
  • 20

1 Answers1

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.]]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • Can you explain what your code does ? what would be the unwrapped version of your code? – user59419 Jun 18 '19 at 05:20
  • I did explain. Remove the brackets, split on the spaces and convert to float. Other than that, go study [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) – Stephen Rauch Jun 18 '19 at 05:22
  • @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. – hpaulj Jun 18 '19 at 05:47