正常读取会报格式错误
p = r'hw1_data/train.csv'
f = np.loadtxt(p, dtype=str, delimiter=',')
print(f)
numpy读取csv文件时,dtype默认为float,有字母时,需要改为str,但是当文件中有中文时,依然报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 0: invalid start byte
。
改变编码格式:
f = np.loadtxt(p, dtype=str, delimiter=',', encoding="unicode_escape")
能够完整输出内容,但是中文就认不到了:
[['¤é´Á' '´ú¯¸' '´ú¶µ' ... '21' '22' '23']
['2014/1/1' 'Â×\xadì' 'AMB_TEMP' ... '15' '15' '15']
后来查资料发现,需要将encoding改为big5,这样就能正常显示中文了:
import numpy as np
import pandas as pd
p = r'hw1_data/train.csv'
f = np.loadtxt(p, dtype=str, delimiter=',', encoding="big5")
# f = pd.read_csv(p, encoding='big5')
print(f)
pandas同理。
显示如下,用pandas读取,显示出来效果更好:
numpy:
[['日期' '測站' '測項' ... '21' '22' '23']
['2014/1/1' '豐原' 'AMB_TEMP' ... '15' '15' '15']
pandas:
日期 測站 測項 0 1 ... 19 20 21 22 23
0 2014/1/1 豐原 AMB_TEMP 14 14 ... 16 15 15 15 15
1 2014/1/1 豐原 CH4 1.8 1.8 ... 1.8 1.8 1.8 1.8 1.8