[Numpy-discussion] printing structured arrays
bruce.schultz at gmail.com
Wed Mar 10 09:06:28 EST 2010
On 10/03/10 10:09, Bruce Schultz wrote:
> On Sat, Mar 6, 2010 at 8:35 AM, Gökhan Sever <gokhansever at gmail.com> wrote:
>> On Fri, Mar 5, 2010 at 8:00 AM, Bruce Schultz <bruce.schultz at gmail.com>
>>> Output is:
>>> ### ndarray
>>> [[ 1. 2. ]
>>> [ 3. 4.1]]
>>> ### structured array
>>> [(1.0, 2.0) (3.0, 4.0999999999999996)]
>> I still couldn't figure out how floating point numbers look nicely on screen
>> in cases like yours (i.e., trying numpy.array2string()) but you can make
>> sure by using numpy.savetxt("file", array, fmt="%.1f") you will always have
>> specified precision in the written file.
> Using numpy.array2string() gives the same format as the output above.
I started looking at how array2string() is implemented, and came up with
this patch which formats my structured array nicely, the same as an
unstructured array. It was mainly done as a proof of concept, so it only
works for floats and I'm probably doing the wrong thing to detect a
structured array by comparing the dtype to void. Maybe someone with
more numpy experience can tell me if I'm on the right track...
=== modified file 'numpy/core/arrayprint.py'
--- numpy/core/arrayprint.py 2010-02-21 16:16:34 +0000
+++ numpy/core/arrayprint.py 2010-03-10 13:48:22 +0000
@@ -219,6 +219,10 @@
elif issubclass(dtypeobj, _nt.unicode_) or \
format_function = repr
+ elif issubclass(dtypeobj, _nt.void):
+ #XXX this is for structured arrays....
+ format_function = StructuredFormatter(a)
+ separator = '\n '
format_function = str
@@ -231,6 +235,17 @@
+ def __init__(self, a):
+ self.data = a
+ self.dtype = a.dtype #XXX use the dtype to build column formatters
+ def __call__(self, x):
+ ff = FloatFormat(self.data.view(float), _float_output_precision,
+ return '[' + ' '.join([ff(n) for n in x]) + ']'
import numeric as _nc
newtup = 
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion