使用numpy的loadtxt函数加载CSV格式的数据时报错
原代码如下:
a, b, c, d, e, f, g, h = np.loadtxt("data.csv", delimiter=",", usecols=(0, 1, 2, 3, 4, 5, 6, 7), unpack=True,skiprows = 1)
错误类型:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb7 in position 8: illegal multibyte sequence
改正方法:
a, b, c, d, e, f, g, h = np.loadtxt("data.csv", delimiter=",", usecols=(0, 1, 2, 3, 4, 5, 6, 7), unpack=True,encoding = "Latin-1" ,dtype=str,skiprows = 1)
添加dtype=str参数会将csv里面的数据转换成str格式,encoding = “Latin-1” ,然后改一下编码格式即可重新运行
若要将数据重新转换回原来的格式,可参考以下代码
a.astype(int) # 使用astype方法转换数据格式