我正在使用标题打印数组的内容。该数组包含非常小的数字,其中python以指数格式打印。在numpy row_stack中使用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不正确。
有什么想法吗? 感谢
答案 0 :(得分: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