如果我的数据包含字符串,如何解决使用np.loadtxt()的问题

时间:2018-12-30 22:07:29

标签: python numpy load

我想使用numpy中的funcion loadtxt,但是我的txt数据中包含字符串。我该如何忽略字符串并仍然保留数据的行和列?

import os
from numpy import loadtxt

filename = 'C:/Users/.../Documents/.../.../.../.../.../.../report.txt'

data = loadtxt(filename)

# That's a sample of the data I am trying to load

1 stats/cope1 2589 -3.519 -0.8423 0.02977 -0.1044 1.133 4.889 0.9278 61 29 14 7.0 -90.6 -9.4
1 stats/cope2 2589 -4.102 -1.134 -0.04528 -0.1969 1.468 8.227 1.194 61 30 15 7.0 -88.2 -6.3

输出:

ValueError: could not convert string to float: stats/pe1

1 个答案:

答案 0 :(得分:0)

data = np.genfromtxt('filename', dtype='str')
data = np.delete(data, 1, 1)
data = [[float(i) for i in data[0]],[float(i) for i in data[1]]]  # type: list
data = np.asarray(data)  # type: numpy.ndarray

data.shape  # (2,10)

print(data)  
# array([[1., 1.133, 4.889, 0.9278, 61., 29. ,14., 7., -90.6 ,  -9.4],
#        [1., 1.468, 8.227, 1.194 , 61., 30., 15., 7., -88.2 ,  -6.3]])