[英]Convert a list of strings into ndarray of floats
I have a list of strings like the following: 我有如下字符串列表:
['0.20115899', '0.111678', '0.10674', '0.05564842', '-0.09271969', '-0.02292056', '-0.04057575', '0.2019901', '-0.05368654', '-0.1708179']
['-2.17182860e-01', '-1.04081273e-01', '7.75325894e-02', '7.51972795e-02', '-7.11168349e-02', '-4.75254208e-02', '-2.94160955e-02']
etc.
etc.
List's name is data_det
. 列表的名称是
data_det
。 I did the following to find the types: 我做了以下工作来找到类型:
for item in data_det:
print(type(item))
for it in item:
print(type(it))
I got 我有
<class 'list'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
etc.
I tried to convert it into ndarray
. 我试图将其转换为
ndarray
。
data_det = numpy.asarray(data_det, dtype=np.float)
But got the error: 但是得到了错误:
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.
Ideally I want each value to be converted to float. 理想情况下,我希望将每个值都转换为浮点型。 How can this be accomplished?
如何做到这一点?
Try this : 尝试这个 :
import numpy as np
l1 = ['0.20115899', '0.111678', '0.10674', '0.05564842', '-0.09271969', '-0.02292056', '-0.04057575', '0.2019901', '-0.05368654', '-0.1708179']
l2 = ['-2.17182860e-01', '-1.04081273e-01', '7.75325894e-02', '7.51972795e-02', '-7.11168349e-02', '-4.75254208e-02', '-2.94160955e-02']
l1 = np.array([float(i) for i in l1])
l2 = np.array([float(i) for i in l2])
print(l1.dtype)
Output : 输出 :
float64
In regards to my comment and your comment. 关于我的评论和您的评论。 Since you said your data is in list of a list format.
既然您说过,您的数据就是列表格式的列表 。 You need to traverse the list.
您需要遍历列表。
You use np.float
to set the values incoming to a float type. 您可以使用
np.float
设置传入浮点类型的值。 Use dtype=object
to set arbitrary types. 使用
dtype=object
设置任意类型。
import numpy as np
# Traverse list of list
def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o
# Your data
values = [('0.20115899', '0.111678'), ('0.211282', '0.342342')]
# Traverse data list of list
values = traverse(values)
# Loop through new values
x = np.asarray([float(value) for value in values], np.float)
# Output
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.