将字符串列表转换为浮点数的numpy数组 [英] Convert list of strings to numpy array of floats

查看:62
本文介绍了将字符串列表转换为浮点数的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串列表,我想将其转换为numpy数组.例如,我有

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]']

我希望输出如下:2 x 7的矩阵

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))

但是我的输出如下:

['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.

推荐答案

只要走直接路线即可.在将结果发送到numpy.array之前,去掉方括号,在空格处分割并转换为float:

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])

测试代码:

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]))

结果:

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

这篇关于将字符串列表转换为浮点数的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆