1. 程式人生 > >pandas使用read_csv()讀取檔案遇到的問題

pandas使用read_csv()讀取檔案遇到的問題

資料檔案:

上海機場 (sh600009)
24.11 3.58
東風汽車 (sh600006) 74.25 1.74
中國國貿 (sh600007) 26.38 2.66
包鋼股份 (sh600010) 61.01 2.35
武鋼股份 (sh600005) 75.85 1.3
浦發銀行 (sh600000) 6.65 0.96

在使用read_csv() API讀取CSV檔案時求取某一列資料比較大小時, df=pd.read_csv(output_file,encoding='gb2312',names=['a','b','c']) df.b>20 報錯 TypeError:'>'not supported between instances of 'str' and 'int' 從返回的錯誤資訊可知應該是資料型別錯誤,讀回來的是‘str’ in : df.dtypes out:       a  object       b  object       c   object       dtype: object 由此可知 df.b 型別是 object 查閱read_csv()文件 配置: dtype : Type name or dict of column -> type, default None

Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} (unsupported with engine='python'). Use str or object to preserve and not interpret dtype.

New in version 0.20.0: support for the Python parser.

可知預設使用‘str’或‘object’儲存 因此在讀取時只需要修改 'dtype' 配置就可以 df=pd.read_csv(output_file,encoding='gb2312',names=['a','b','c'],dtype={'b':np.folat64})