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)
| 2557 | |
| 2558 | |
| 2559 | def flatten_structured_array(a): |
| 2560 | """ |
| 2561 | Flatten a structured array. |
| 2562 | |
| 2563 | The data type of the output is chosen such that it can represent all of the |
| 2564 | (nested) fields. |
| 2565 | |
| 2566 | Parameters |
| 2567 | ---------- |
| 2568 | a : structured array |
| 2569 | |
| 2570 | Returns |
| 2571 | ------- |
| 2572 | output : masked array or ndarray |
| 2573 | A flattened masked array if the input is a masked array, otherwise a |
| 2574 | standard ndarray. |
| 2575 | |
| 2576 | Examples |
| 2577 | -------- |
| 2578 | >>> import numpy as np |
| 2579 | >>> ndtype = [('a', int), ('b', float)] |
| 2580 | >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) |
| 2581 | >>> np.ma.flatten_structured_array(a) |
| 2582 | array([[1., 1.], |
| 2583 | [2., 2.]]) |
| 2584 | |
| 2585 | """ |
| 2586 | |
| 2587 | def flatten_sequence(iterable): |
| 2588 | """ |
| 2589 | Flattens a compound of nested iterables. |
| 2590 | |
| 2591 | """ |
| 2592 | for elm in iter(iterable): |
| 2593 | if hasattr(elm, "__iter__") and not isinstance(elm, (str, bytes)): |
| 2594 | yield from flatten_sequence(elm) |
| 2595 | else: |
| 2596 | yield elm |
| 2597 | |
| 2598 | a = np.asanyarray(a) |
| 2599 | inishape = a.shape |
| 2600 | a = a.ravel() |
| 2601 | if isinstance(a, MaskedArray): |
| 2602 | out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) |
| 2603 | out = out.view(MaskedArray) |
| 2604 | out._mask = np.array([tuple(flatten_sequence(d.item())) |
| 2605 | for d in getmaskarray(a)]) |
| 2606 | else: |
| 2607 | out = np.array([tuple(flatten_sequence(d.item())) for d in a]) |
| 2608 | if len(inishape) > 1: |
| 2609 | newshape = list(out.shape) |
| 2610 | newshape[0] = inishape |
| 2611 | out = out.reshape(tuple(flatten_sequence(newshape))) |
| 2612 | return out |
| 2613 | |
| 2614 | |
| 2615 | def _arraymethod(funcname, onmask=True): |
searching dependent graphs…