1

I fail to format a numpy-array when saving with savetxt:

from numpy import *

a = loadtxt('frequenz.txt')
b = sum(a[0:10,1:4], 1)/3-20741
savetxt('solution.txt', b, fmt='%.2f', delimiter='\t', header='average')

There is an error displayed:

fh.write(asbytes(format % tuple(row) + newline))
UnboundLocalError: local variable 'format' referenced before assignment

When saving the values without fmt it works, but I want to have only 2 decimals:

from numpy import *

a = loadtxt('frequenz.txt')
b = sum(a[0:10,1:4], 1)/3-20741
savetxt('solution.txt', b, delimiter='\t', header='average')

solution.txt:

# average
3.666666666667879326e+00
6.666666666667879326e+00
9.333333333332120674e+00
1.300000000000000000e+01
1.533333333333212067e+01
1.833333333333212067e+01
2.133333333333212067e+01
2.466666666666787933e+01
2.766666666666787933e+01
3.066666666666787933e+01

frequenz.txt:

#0  20741   20741   20741
6   20745   20745   20744   20739   20739   20738
12  20748   20747   20748   20736   20736   20736
18  20750   20751   20750   20732   20733   20732
24  20754   20754   20754   20730   20730   20730
30  20756   20756   20757   20727   20727   20726   
36  20760   20759   20759   20723   20723   20724
42  20762   20762   20763   20721   20721   20720
48  20766   20766   20765   20718   20718   20718
54  20768   20769   20769   20715   20715   20714
60  20771   20772   20772   20712   20712   20712   

Thank you for your help! Martin

4

1 回答 1

1

我的解决方案:我总是在编辑器 BBEdit 中输入 python 代码,然后在终端中运行它。这不起作用并给出错误。直接将其输入终端可以正常工作。我的 python 文档的默认头是

from __future__ import (print_function, division, unicode_literals, absolute_import)

该错误是由

unicode_literals

也许它可以帮助其他人。问候。

于 2013-10-20T18:49:54.097 回答