Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. Thi
(a, align=False, recurse=False)
| 767 | |
| 768 | @array_function_dispatch(_repack_fields_dispatcher) |
| 769 | def repack_fields(a, align=False, recurse=False): |
| 770 | """ |
| 771 | Re-pack the fields of a structured array or dtype in memory. |
| 772 | |
| 773 | The memory layout of structured datatypes allows fields at arbitrary |
| 774 | byte offsets. This means the fields can be separated by padding bytes, |
| 775 | their offsets can be non-monotonically increasing, and they can overlap. |
| 776 | |
| 777 | This method removes any overlaps and reorders the fields in memory so they |
| 778 | have increasing byte offsets, and adds or removes padding bytes depending |
| 779 | on the `align` option, which behaves like the `align` option to |
| 780 | `numpy.dtype`. |
| 781 | |
| 782 | If `align=False`, this method produces a "packed" memory layout in which |
| 783 | each field starts at the byte the previous field ended, and any padding |
| 784 | bytes are removed. |
| 785 | |
| 786 | If `align=True`, this methods produces an "aligned" memory layout in which |
| 787 | each field's offset is a multiple of its alignment, and the total itemsize |
| 788 | is a multiple of the largest alignment, by adding padding bytes as needed. |
| 789 | |
| 790 | Parameters |
| 791 | ---------- |
| 792 | a : ndarray or dtype |
| 793 | array or dtype for which to repack the fields. |
| 794 | align : boolean |
| 795 | If true, use an "aligned" memory layout, otherwise use a "packed" layout. |
| 796 | recurse : boolean |
| 797 | If True, also repack nested structures. |
| 798 | |
| 799 | Returns |
| 800 | ------- |
| 801 | repacked : ndarray or dtype |
| 802 | Copy of `a` with fields repacked, or `a` itself if no repacking was |
| 803 | needed. |
| 804 | |
| 805 | Examples |
| 806 | -------- |
| 807 | |
| 808 | >>> from numpy.lib import recfunctions as rfn |
| 809 | >>> def print_offsets(d): |
| 810 | ... print("offsets:", [d.fields[name][1] for name in d.names]) |
| 811 | ... print("itemsize:", d.itemsize) |
| 812 | ... |
| 813 | >>> dt = np.dtype('u1, <i8, <f8', align=True) |
| 814 | >>> dt |
| 815 | dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['u1', '<i8', '<f8'], \ |
| 816 | 'offsets': [0, 8, 16], 'itemsize': 24}, align=True) |
| 817 | >>> print_offsets(dt) |
| 818 | offsets: [0, 8, 16] |
| 819 | itemsize: 24 |
| 820 | >>> packed_dt = rfn.repack_fields(dt) |
| 821 | >>> packed_dt |
| 822 | dtype([('f0', 'u1'), ('f1', '<i8'), ('f2', '<f8')]) |
| 823 | >>> print_offsets(packed_dt) |
| 824 | offsets: [0, 1, 9] |
| 825 | itemsize: 17 |
| 826 |