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

Function apply_along_fields

numpy/lib/recfunctions.py:1182–1222  ·  view source on GitHub ↗

Apply function 'func' as a reduction across fields of a structured array. This is similar to `apply_along_axis`, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from `numpy.result_type`

(func, arr)

Source from the content-addressed store, hash-verified

1180
1181@array_function_dispatch(_apply_along_fields_dispatcher)
1182def apply_along_fields(func, arr):
1183 """
1184 Apply function 'func' as a reduction across fields of a structured array.
1185
1186 This is similar to `apply_along_axis`, but treats the fields of a
1187 structured array as an extra axis. The fields are all first cast to a
1188 common type following the type-promotion rules from `numpy.result_type`
1189 applied to the field's dtypes.
1190
1191 Parameters
1192 ----------
1193 func : function
1194 Function to apply on the "field" dimension. This function must
1195 support an `axis` argument, like np.mean, np.sum, etc.
1196 arr : ndarray
1197 Structured array for which to apply func.
1198
1199 Returns
1200 -------
1201 out : ndarray
1202 Result of the recution operation
1203
1204 Examples
1205 --------
1206
1207 >>> from numpy.lib import recfunctions as rfn
1208 >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],
1209 ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')])
1210 >>> rfn.apply_along_fields(np.mean, b)
1211 array([ 2.66666667, 5.33333333, 8.66666667, 11. ])
1212 >>> rfn.apply_along_fields(np.mean, b[['x', 'z']])
1213 array([ 3. , 5.5, 9. , 11. ])
1214
1215 """
1216 if arr.dtype.names is None:
1217 raise ValueError('arr must be a structured array')
1218
1219 uarr = structured_to_unstructured(arr)
1220 return func(uarr, axis=-1)
1221 # works and avoids axis requirement, but very, very slow:
1222 #return np.apply_along_axis(func, -1, uarr)
1223
1224def _assign_fields_by_name_dispatcher(dst, src, zero_unassigned=None):
1225 return dst, src

Callers 1

Calls 2

funcFunction · 0.70

Tested by 1