Casts a structured array to a new dtype using assignment by field-name. This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new
(array, required_dtype)
| 1267 | |
| 1268 | @array_function_dispatch(_require_fields_dispatcher) |
| 1269 | def require_fields(array, required_dtype): |
| 1270 | """ |
| 1271 | Casts a structured array to a new dtype using assignment by field-name. |
| 1272 | |
| 1273 | This function assigns from the old to the new array by name, so the |
| 1274 | value of a field in the output array is the value of the field with the |
| 1275 | same name in the source array. This has the effect of creating a new |
| 1276 | ndarray containing only the fields "required" by the required_dtype. |
| 1277 | |
| 1278 | If a field name in the required_dtype does not exist in the |
| 1279 | input array, that field is created and set to 0 in the output array. |
| 1280 | |
| 1281 | Parameters |
| 1282 | ---------- |
| 1283 | a : ndarray |
| 1284 | array to cast |
| 1285 | required_dtype : dtype |
| 1286 | datatype for output array |
| 1287 | |
| 1288 | Returns |
| 1289 | ------- |
| 1290 | out : ndarray |
| 1291 | array with the new dtype, with field values copied from the fields in |
| 1292 | the input array with the same name |
| 1293 | |
| 1294 | Examples |
| 1295 | -------- |
| 1296 | |
| 1297 | >>> from numpy.lib import recfunctions as rfn |
| 1298 | >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) |
| 1299 | >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) |
| 1300 | array([(1., 1), (1., 1), (1., 1), (1., 1)], |
| 1301 | dtype=[('b', '<f4'), ('c', 'u1')]) |
| 1302 | >>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) |
| 1303 | array([(1., 0), (1., 0), (1., 0), (1., 0)], |
| 1304 | dtype=[('b', '<f4'), ('newf', 'u1')]) |
| 1305 | |
| 1306 | """ |
| 1307 | out = np.empty(array.shape, dtype=required_dtype) |
| 1308 | assign_fields_by_name(out, array) |
| 1309 | return out |
| 1310 | |
| 1311 | |
| 1312 | def _stack_arrays_dispatcher(arrays, defaults=None, usemask=None, |