MCPcopy Create free account
hub / github.com/numpy/numpy / flatten_structured_array

Function flatten_structured_array

numpy/ma/core.py:2489–2541  ·  view source on GitHub ↗

Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input i

(a)

Source from the content-addressed store, hash-verified

2487
2488
2489def flatten_structured_array(a):
2490 """
2491 Flatten a structured array.
2492
2493 The data type of the output is chosen such that it can represent all of the
2494 (nested) fields.
2495
2496 Parameters
2497 ----------
2498 a : structured array
2499
2500 Returns
2501 -------
2502 output : masked array or ndarray
2503 A flattened masked array if the input is a masked array, otherwise a
2504 standard ndarray.
2505
2506 Examples
2507 --------
2508 >>> ndtype = [('a', int), ('b', float)]
2509 >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
2510 >>> np.ma.flatten_structured_array(a)
2511 array([[1., 1.],
2512 [2., 2.]])
2513
2514 """
2515
2516 def flatten_sequence(iterable):
2517 """
2518 Flattens a compound of nested iterables.
2519
2520 """
2521 for elm in iter(iterable):
2522 if hasattr(elm, '__iter__'):
2523 yield from flatten_sequence(elm)
2524 else:
2525 yield elm
2526
2527 a = np.asanyarray(a)
2528 inishape = a.shape
2529 a = a.ravel()
2530 if isinstance(a, MaskedArray):
2531 out = np.array([tuple(flatten_sequence(d.item())) for d in a._data])
2532 out = out.view(MaskedArray)
2533 out._mask = np.array([tuple(flatten_sequence(d.item()))
2534 for d in getmaskarray(a)])
2535 else:
2536 out = np.array([tuple(flatten_sequence(d.item())) for d in a])
2537 if len(inishape) > 1:
2538 newshape = list(out.shape)
2539 newshape[0] = inishape
2540 out.shape = tuple(flatten_sequence(newshape))
2541 return out
2542
2543
2544def _arraymethod(funcname, onmask=True):

Callers 2

recordmaskMethod · 0.85

Calls 5

flatten_sequenceFunction · 0.85
getmaskarrayFunction · 0.85
itemMethod · 0.80
ravelMethod · 0.45
viewMethod · 0.45

Tested by 1