Question

What's the right way to round each item in the par1 and par2 columns of this array to 6 decimal places. Below is what I tried so far but I'm getting a strange error.

(I guess it also wouldn't work because it would round the first column?)

a = numpy.array([('54641', 5.2283950300822005e-19, 0.99986935998398196),
   ('19463068', 1.9641846381816301e-11, 3.9584362981756201e-24),
   ('19500889', 3.0296847410896202e-11, 1.05569703377661e-11),
   ('19528632', 3.5188395912917703e-11, 1.4213535554705201e-09)], 
  dtype=[('pos', 'S100'), ('par1', '<f8'), ('par2', '<f8')])
a = numpy.around(a, decimals=6)

Strange Error (any idea why it's saying this?)

Traceback (most recent call last):
  File "msg/combine.py", line 244, in <module>
    a = numpy.around(a, decimals=6)
  File "/usr/local/msg/lib/python2.6/site-packages/numpy/core/fromnumeric.py", line 2611, in around
    return round(decimals, out)
TypeError: return arrays must be of ArrayType
Was it helpful?

Solution

Not sure if you can do this without loops:

>>> for col in ['par1','par2']:
...     a[col] = numpy.around(a[col],2)
...
>>> a
array([('54641', 0.0, 1.0), ('19463068', 0.0, 0.0), ('19500889', 0.0, 0.0),
       ('19528632', 0.0, 0.0)],
      dtype=[('pos', 'S100'), ('par1', '<f8'), ('par2', '<f8')])

Of course you can use pandas for structured arrays:

>>> import pandas as pd
>>> data = pd.DataFrame(a)
>>> data[['par1','par2']] = numpy.around(data[['par1','par2']], 2)
>>> data
        pos  par1  par2
0     54641     0     1
1  19463068     0     0
2  19500889     0     0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top