无法将字符串转换为numpy ndarray中的float

问题描述 投票:0回答:1

我一直在阅读fer 2013 csv文件,包含三列情感,像素值和用法。据说像素值以字符串格式给出,我想将我的像素值从0-255重新缩放到0-1之间,所以我需要将它转换为int / float然后我才能做任何数学对他们的操作。

我首先尝试使用pandas read_csv函数读取csv文件然后使用iloc我在一个名为x_tr的变量中读取像素值的值。然后在打印它的值时,它将其d类型显示为object.confused on too.x_tr是numpy ndarray然后我应该如何将其转换为整数值。我尝试了x_tr.astype(np.float),但它放弃了代码中提到的错误。

x_tr = train.iloc[:,1].values
x_tr

The screenshot of what x_tr contains

我试图转换为浮动

x_tr = train.iloc[:,1].values
x_tr = x_tr.astype(np.float) 

我得到的是错误

enter image description here

请帮忙。

python-3.x numpy numpy-ndarray
1个回答
1
投票

不要将pixel转换为数组,而是将其视为一个简单的字符串。然后使用numpy.fromstring()方法。这是一个供参考的例子。

>>> s = '1 2 3 4'
>>> f = np.fromstring(s, dtype=float, sep=' ')
>>> f
array([1., 2., 3., 4.])
© www.soinside.com 2019 - 2024. All rights reserved.