我不能使用numpy astype将字符串转换为float

时间:2018-01-22 08:03:07

标签: python arrays numpy

我想使用np.array将列表转换为数组,然后将数据转换为float。但数据类型是U15,我不知道它是什么。我可以通过array2 [0:2] .astype(np.float)将多个行数据转换为float,但不能将整个数组转换为float。在for循环中所做的是筛选合格数据。

数据超过100万,部分数据是:

33,Jogging,49105962326000,-0.6946377,12.680544,0.50395286;
33,Jogging,49106062271000,5.012288,11.264028,0.95342433;
33,Jogging,49106112167000,4.903325,10.882658,-0.08172209;
33,Jogging,49106222305000,-0.61291564,18.496431,3.0237172;
33,Jogging,49106332290000,-1.1849703,12.108489,7.205164;
33,Jogging,49106442306000,1.3756552,-2.4925237,-6.510526;

代码如下:

import numpy as np
file = open("WISDM_ar_v1.1_raw.txt", "r")
list_arr = file.readlines()

length = len(list_arr)
list1 = []
#print(length)
for i in range(length):
    list_arr[i] = list_arr[i].rstrip("\n")
    list_arr[i] = list_arr[i].rstrip(";")
    list_arr[i] = list_arr[i].split(",")
    if len(list_arr[i]) == 6:
        list1.append(list_arr[i])
    else:
        pass

array1 = np.array(list1,dtype=str)
print(array1.dtype)
array2 = np.delete(array1, [0,1], axis=1)
print(array2[0:2])
print(array2.dtype)
array2 = array2.astype(np.float)
print(array2)

错误是:

<U15
[['49105962326000' '-0.6946377' '12.680544' '0.50395286']
 ['49106062271000' '5.012288' '11.264028' '0.95342433']]
<U15
Traceback (most recent call last):
  File "D:/Anaconda/network/.idea/testfloat.py", line 22, in <module>
    array2 = array2.astype(np.float)
ValueError: could not convert string to float:

0 个答案:

没有答案