Skip to content

Commit 7c5163a

Browse files
authored
Merge pull request #8160 from skwbc/issue#5692
BUG: fix _array2string for structured array (issue #5692)
2 parents 0a02bb6 + 3d75c3f commit 7c5163a

2 files changed

Lines changed: 81 additions & 33 deletions

File tree

‎numpy/core/arrayprint.py‎

Lines changed: 66 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -234,27 +234,23 @@ def _boolFormatter(x):
234234
def repr_format(x):
235235
return repr(x)
236236

237-
def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
238-
prefix="", formatter=None):
239-
240-
if max_line_width is None:
241-
max_line_width = _line_width
242-
243-
if precision is None:
244-
precision = _float_output_precision
245-
246-
if suppress_small is None:
247-
suppress_small = _float_output_suppress_small
248-
249-
if formatter is None:
250-
formatter = _formatter
251-
252-
if a.size > _summaryThreshold:
253-
summary_insert = "..., "
254-
data = _leading_trailing(a)
255-
else:
256-
summary_insert = ""
257-
data = ravel(asarray(a))
237+
def _get_format_function(data, precision, suppress_small, formatter):
238+
"""
239+
find the right formatting function for the dtype_
240+
"""
241+
dtype_ = data.dtype
242+
if dtype_.fields is not None:
243+
format_functions = []
244+
for descr in dtype_.descr:
245+
field_name = descr[0]
246+
field_values = data[field_name]
247+
if len(field_values.shape) <= 1:
248+
format_function = _get_format_function(
249+
field_values, precision, suppress_small, formatter)
250+
else:
251+
format_function = repr_format
252+
format_functions.append(format_function)
253+
return StructureFormat(format_functions)
258254

259255
formatdict = {'bool': _boolFormatter,
260256
'int': IntegerFormat(data),
@@ -289,31 +285,56 @@ def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
289285
if key in fkeys:
290286
formatdict[key] = formatter[key]
291287

292-
# find the right formatting function for the array
293-
dtypeobj = a.dtype.type
288+
dtypeobj = dtype_.type
294289
if issubclass(dtypeobj, _nt.bool_):
295-
format_function = formatdict['bool']
290+
return formatdict['bool']
296291
elif issubclass(dtypeobj, _nt.integer):
297292
if issubclass(dtypeobj, _nt.timedelta64):
298-
format_function = formatdict['timedelta']
293+
return formatdict['timedelta']
299294
else:
300-
format_function = formatdict['int']
295+
return formatdict['int']
301296
elif issubclass(dtypeobj, _nt.floating):
302297
if issubclass(dtypeobj, _nt.longfloat):
303-
format_function = formatdict['longfloat']
298+
return formatdict['longfloat']
304299
else:
305-
format_function = formatdict['float']
300+
return formatdict['float']
306301
elif issubclass(dtypeobj, _nt.complexfloating):
307302
if issubclass(dtypeobj, _nt.clongfloat):
308-
format_function = formatdict['longcomplexfloat']
303+
return formatdict['longcomplexfloat']
309304
else:
310-
format_function = formatdict['complexfloat']
305+
return formatdict['complexfloat']
311306
elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)):
312-
format_function = formatdict['numpystr']
307+
return formatdict['numpystr']
313308
elif issubclass(dtypeobj, _nt.datetime64):
314-
format_function = formatdict['datetime']
309+
return formatdict['datetime']
315310
else:
316-
format_function = formatdict['numpystr']
311+
return formatdict['numpystr']
312+
313+
def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
314+
prefix="", formatter=None):
315+
316+
if max_line_width is None:
317+
max_line_width = _line_width
318+
319+
if precision is None:
320+
precision = _float_output_precision
321+
322+
if suppress_small is None:
323+
suppress_small = _float_output_suppress_small
324+
325+
if formatter is None:
326+
formatter = _formatter
327+
328+
if a.size > _summaryThreshold:
329+
summary_insert = "..., "
330+
data = _leading_trailing(a)
331+
else:
332+
summary_insert = ""
333+
data = ravel(asarray(a))
334+
335+
# find the right formatting function for the array
336+
format_function = _get_format_function(data, precision,
337+
suppress_small, formatter)
317338

318339
# skip over "["
319340
next_line_prefix = " "
@@ -758,3 +779,15 @@ def __call__(self, x):
758779
return self._nat
759780
else:
760781
return self.format % x.astype('i8')
782+
783+
784+
class StructureFormat(object):
785+
def __init__(self, format_functions):
786+
self.format_functions = format_functions
787+
self.num_fields = len(format_functions)
788+
789+
def __call__(self, x):
790+
s = "("
791+
for field, format_function in zip(x, self.format_functions):
792+
s += format_function(field) + ", "
793+
return (s[:-2] if 1 < self.num_fields else s[:-1]) + ")"

‎numpy/core/tests/test_arrayprint.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,21 @@ def _format_function(x):
113113
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
114114
'[abcabc defdef]')
115115

116+
def test_structure_format(self):
117+
dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
118+
x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
119+
assert_equal(np.array2string(x),
120+
"[('Sarah', array([ 8., 7.])) ('John', array([ 6., 7.]))]")
121+
122+
# for issue #5692
123+
A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
124+
A[5:].fill(np.nan)
125+
assert_equal(np.array2string(A),
126+
"[('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) " +
127+
"('1970-01-01T00:00:00',)\n ('1970-01-01T00:00:00',) " +
128+
"('1970-01-01T00:00:00',) ('NaT',) ('NaT',)\n " +
129+
"('NaT',) ('NaT',) ('NaT',)]")
130+
116131

117132
class TestPrintOptions:
118133
"""Test getting and setting global print options."""

0 commit comments

Comments
 (0)