numPy gives nan while reading a negative number from a file

ぐ巨炮叔叔 提交于 2019-12-11 07:05:15

问题


I tried to read the contents of a 3x3 matrix stored in a text file having the following values.

−30  10  20  
 10  40 −50  
 20 −50 −10

I used numpy.genfromtxt as follows but when it gave nan in place of negative data values.

data = np.genfromtxt('file.txt',delimiter=' ')
print(data)
print(type(data[0][0]))

But the datatype of the negative value still shows float64:

I also tried reading the values as a list and then converting to numpy array but that also didn't work.

Is there any other way I can read negative values as a numpy array from a file input?


回答1:


You've got U+2212 MINUS SIGN characters in your file, not the U+002D HYPHEN-MINUS people usually think of as the minus sign character. genfromtxt doesn't handle that character. Replace the minus sign characters with hyphen-minuses before trying to parse the data.




回答2:


Try this code instead:

data=pd.read_csv("data.txt",delimiter=",")
data = DataFrame(data)


来源:https://stackoverflow.com/questions/52241853/numpy-gives-nan-while-reading-a-negative-number-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!