Convert list of strings to numpy array of floats

随声附和 提交于 2021-01-29 06:24:19

问题


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.


回答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.]]


来源:https://stackoverflow.com/questions/56642038/convert-list-of-strings-to-numpy-array-of-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!