2014-05-08 130 views
1

我想尋求指導我在pandas.read_csv例程中發現的問題的補救步驟。當我使用pd.to_csv將一個長整數存儲到一個文件中時,它將數據存儲好 - 但是當我使用pd.read_csv讀取它時,它與最後3位數字混淆。當我嘗試使用to_csv(不進行任何編輯)再次將其保存時,生成的CSV文件中的數字與原始CSV文件不同。我下面所示的問題(注意如何4321113141090630389成爲4321113141090630400和4321583677327450765成爲4321583677327450880):與pd.read_csv截斷問題

通過pd.to_csv創建原始CSV文件:

grep -e 321583677327450 -e 321113141090630 orig.piece 
orig.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765 
orig.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389 

import pandas as pd 
import numpy as np 

orig = pd.read_csv('orig.piece') 
orig.dtypes 
Unnamed: 0 int64 
aa object 
act float64 
... 
... 
s_act float64 
dtype: object 

>orig['s_act'].head(6) 
0 NaN 
1 4.321584e+18 
2 4.321974e+18 
3 4.321494e+18 
4 4.321283e+18 
5 4.321113e+18 
Name: s_act, dtype: float64 

>orig['s_act'].fillna(0).astype(int).head(6) 
0 0 
1 4321583677327450880 
2 4321973950881710336 
3 4321493786516159488 
4 4321282586859217408 
5 4321113141090630400 

>orig.to_csv('convert.piece') 

grep -e 321583677327450 -e 321113141090630 orig.piece convert.piece 
orig.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765 
orig.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389 
convert.piece:1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4.321583677327451e+18 
convert.piece:5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4.3211131410906304e+18 

請你幫助我理解爲什麼read_csv攪亂最後三位數字?它甚至不是圓整的問題,數字是完全不同的(如4321583677327450765變爲4321583677327450880以上)是否因爲科學記數法出現 - 我們如何禁用它並讓大熊貓將這些數據視爲絕對對象/字符串或計劃整數/浮動?

+0

btw,當我說'orig = pd.read_csv('orig.piece',dtype = str)'時,問題就消失了。但是,這有什麼缺點嗎?此外,這聽起來像一個解決方法,而不是一個修復。 – user3615154

回答

3

這是浮點錯誤。因爲s_act列有缺失值(pandas沒有整數缺失值),所以它在s_act中讀取dtype = float(dtypes在pandas的列級定義)。所以你基本上是看到以下內容:

>>> x = 4321113141090630389 
>>> float(x) 
4.32111314109063e+18 
>>> int(float(x)) 
4321113141090630144 

在解決方案方面,你可以的s_act的D型改變,當你在讀它(所產生的D型將是oject)的字符串。例如:

data = """ 
id,val,x 
1,4321113141090630389,4 
2,,5 
3,200,4 
""" 

df = pd.read_csv(StringIO(data),header=True,dtype={'val':str}) 
print df 

    id     val x 
0 1 4321113141090630389 4 
1 2     NaN 5 
2 3     200 4 

print df.info() 

<class 'pandas.core.frame.DataFrame'> 
Int64Index: 3 entries, 0 to 2 
Data columns (total 3 columns): 
id  3 non-null int64 
val 2 non-null object 
x  3 non-null int64 

df['val'] = df['val'].fillna(0).astype(int) 
print df 

    id     val x 
0 1 4321113141090630389 4 
1 2     0 5 
2 3     200 4