问题
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