2012-03-02 78 views
1

我正在打印帶有標題的數組內容。該數組包含非常小的數字,python以指數格式打印。使用csv編寫器和標頭在numpy row_stack中打印時,指數會被截斷。當打印沒有標題時,指數顯示。Python csv作家截斷數字格式

版本A:

print t 
[[ 5.16535888e-06 4.38980952e+02] 
[ 1.34684766e-05 3.37237262e+02] 
[ 7.95903202e-06 6.45989985e+02] 
[ 8.35716563e-06 3.66632398e+02] 
[ 9.39419622e-06 7.14825200e+01]] 

版本B:

# print in table form 
writer = csv.writer(sys.stdout, delimiter="\t")   
writer.writerows([komponents]) 
writer.writerows(np.row_stack((t))) 
>>> 
col1 col2 
5.16535887883e-06 438.980952441 
1.34684765805e-05 337.237261686 
7.95903202041e-06 645.989985081 
8.35716563314e-06 366.632397875 
9.39419621582e-06 71.4825200296 

版本C:

# print in table form 
writer = csv.writer(sys.stdout, delimiter="\t")  
writer.writerows(np.row_stack((komponents, t))) 
>>> 
col1 col2 
5.165358 438.9809 
1.346847 337.2372 
7.959032 645.9899 
8.357165 366.6323 
9.394196 71.48252 

顯然,版本C是不正確的。

任何想法? 謝謝

回答

2

問題是你強制浮點值的數據類型。當您撥打numpy.row_stack時,數據類型將變成一個字符串。例如:

>>> x = numpy.array([1.34684766e-05, 6.45989985e+02]) 
>>> s = numpy.array(["col1", "col2"]) 
>>> numpy.row_stack((x,s)) 
array([['1.346847', '645.9899'], 
     ['col1', 'col2']], 
     dtype='|S8') 

我建議使用numpy.savetxt來做到這一點。例如:

>>> import numpy 
>>> t = numpy.array([[ 5.16535888e-06, 4.38980952e+02], 
... [ 1.34684766e-05, 3.37237262e+02], 
... [ 7.95903202e-06, 6.45989985e+02], 
... [ 8.35716563e-06, 3.66632398e+02], 
... [ 9.39419622e-06, 7.14825200e+01]]) 
>>> komponents = numpy.array([["col1", "col2"]]) 
>>> 
>>> import StringIO 
>>> s = StringIO.StringIO() 
>>> numpy.savetxt(s, komponents, fmt="%s", delimiter="\t") 
>>> numpy.savetxt(s, x, delimiter="\t") 
>>> print s.getvalue() 
col1 col2 
5.165358879999999622e-06 4.389809520000000020e+02 
1.346847660000000055e-05 3.372372619999999870e+02 
7.959032020000000055e-06 6.459899850000000470e+02 
8.357165630000000265e-06 3.666323980000000233e+02 
9.394196219999999191e-06 7.148251999999999384e+01