2016-03-29 9 views
0

私は、1つまたは複数のcsvファイルを読み込み、連結して全体を1つの新しいcsvファイルに書き込むPythonスクリプトを作成しました。私は、この操作中に特定の値がわずかに増減されていることに気付きました。例として:Python Pandasは浮動小数点の値を変更します

オリジナルCSV:

Index SomeValue 
0.000000 0.000 
1.000000 0.000 
2.000000 0.000 
3.000000 0.000 
4.000000 2.527 
5.000000 0.000 

保存したCSV:

Index SomeValue 
0.0 0.0 
1.0 0.0 
2.0 0.0 
3.0 0.0 
4.0 2.5269999999999997 
5.0 0.0 

これは私にはフルスケール誤差のように見えますが、私はそれを原因かわかりません。ループ内で呼び出された私のスクリプトのパンダコア、次のとおりです。

l_tmpCsv_st = pd.read_csv(l_listElement_tc, sep='\t', index_col=0) 
l_listOfCsvFiles_tst.append(l_tmpCsv_st) 
# Fills in nan cells with the value "missing" to distinguish betweens a true nan and a missing value due to lacking padding 
l_listOfCsvFiles_tst[-1] = l_listOfCsvFiles_tst[-1].fillna(value='missing') 

# Concatenating csv file with previous ones 
csvFusion = pd.concat([csvFusion, l_listOfCsvFiles_tst[-1]], axis=1) 

そして、ループの後:

# Padding missing values of lower frequency files 
csvFusion = csvFusion.fillna(method='pad') 
# Determinating which columns need to be deleted (all "Unnamed" columns are panda-error results and need to be removed) 
l_listColumnsToDelete_tst = [col for col in csvFusion.columns if 'Unnamed' in col] 
# Dropping these columns 
csvFusion.drop(l_listColumnsToDelete_tst, axis=1, inplace=True) 
# Writing full stuff to file 
csvFusion.to_csv(l_endFile_tc, sep='\t', decimal=',', na_rep='-') 

私のスクリプトの残りの部分はパンダには無関係であり、唯一の可読性を害することとなります、コピー/貼り付けから削除しました。

どうすればこの問題を回避できますか?事前に

おかげで、

版:

それは確かに浮動小数点エラーでした。十分に高い数字にすべての値を丸め、それを解決:

for col in csvFusion.columns: 
    csvFusion[col] = csvFusion[col].round(15) 
+0

エラーメッセージはありますか? –

+0

浮動小数点精度で行う可能性が高いため、保存精度は表示精度よりも高くなります。 – EdChum

+0

これは完全に浮動小数点の前兆のようです。あなたは、電卓で、すべての数字が厳密に書かれているわけではないことを知っていますか? –

答えて

0

私は浮動小数点precissionので、あなたが、to_csvfloat_formatをパラメータ必要だと思う:私はあなたがroundを使用することができると思う

print df.to_csv(float_format='%.3f') 
Index,SomeValue 
0.000,0.000 
1.000,0.000 
2.000,0.000 
3.000,0.000 
4.000,2.527 
5.000,0.000 

df['SomeValue'] = df['SomeValue'].round(3) 
+0

しかし、それは実際には番号がおそらくhos answerで示されたものであるという事実を変えることはありません。 –

+0

私は異なるサイズのいくつかの値を保存しています。私はわずか3桁の例を提供しましたが、いくつかの値はより高い精度を持つかもしれません。そして、私の最終ファイルを膨らませるので、%.15fにすべての数値を格納するという考えは本当に好きではありません。 – Domack

+0

はい、ご理解ください。使用可能な['round'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.round.html)。 'df ['SomeValue'] = df ['SomeValue']。round(3)'? – jezrael

関連する問題