2

I'm a beginner in python and easily get stucked and confused...

When I read a file which contains a table with numbers with digits, it reads it as an numpy.ndarray

Python is changing the display of the numbers. For example: In the input file i have this number: 56143.0254154 and in the output file the number is written as: 5.61430254e+04

but i want to keep the first format in the output file. i tried to use the string.format or locale.format functions but it doesn't work

Can anybody help me to do this?

Thanks! Ruxy

Ruxy
  • 21
  • 2

3 Answers3

2

Try numpy.set_printoptions() -- there you can e.g. specify the number of digits that are printed and suppress the scientific notation. For example, numpy.set_printoptions(precision=8,suppress=True) will print 8 digits and no "...e+xx".

Jan
  • 4,932
  • 1
  • 26
  • 30
  • does this work when saving the array via `np.savetxt()`. thanks! – ryanjdillon Mar 31 '14 at 15:49
  • After testing, it looks like it doesn't. It is still necessary to set the format via `np.savetxt(... ,fmt='%f')` etc. Info on formatting can be [found here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html). – ryanjdillon Mar 31 '14 at 17:55
1

If you are printing a numpy array, you can control the format of the different data types by using the set_printoptions function. For example:

In [39]: a = array([56143.0254154, 1.234, 0.012345])

In [40]: print(a)
[  5.61430254e+04   1.23400000e+00   1.23450000e-02]

In [41]: set_printoptions(formatter=dict(float=lambda t: "%14.7f" % t))

In [42]: print(a)
[ 56143.0254154      1.2340000      0.0123450]
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
0

You must create a formatted string. Assuming variable number contains the number you want to print, in Python 2.7 or 3, you could use

print("{:20.7f}".format(number))

whereas in Python 2:

print "%20.7f" % number

Alternatively, if you use Numpy routines to write out the array, use the method suggested by Warren.

Bálint Aradi
  • 3,754
  • 16
  • 22