NumPy ndarray.getfield()
The numpy.ndarray.getfield()
method extracts a specific field from a structured NumPy array. It allows retrieving values from an array that has a defined dtype
with multiple fields.
Syntax
ndarray.getfield(dtype, offset=0)
Parameters
Parameter | Type | Description |
---|---|---|
dtype | data-type | The data type of the field to be retrieved. |
offset | int, optional | Byte offset from the start of the field, default is 0 . |
Return Value
Returns a new array containing the extracted field values. The shape of the output remains the same as the original array, but only the selected field values are included.
Examples
1. Extracting a Specific Field from a Structured Array
In this example, we define a structured NumPy array with multiple fields and extract a specific field using getfield()
.
import numpy as np
# Define a structured array with two fields: 'name' (string) and 'age' (integer)
dtype = np.dtype([('name', 'S10'), ('age', np.int32)])
data = np.array([('Alice', 25), ('Bob', 30), ('Charlie', 22)], dtype=dtype)
# Extract only the 'age' field using getfield
age_field = data.getfield(np.int32, offset=10)
print(age_field)
Output:
[25 30 22]
Here, getfield()
retrieves only the integer field age
, returning an array with the corresponding values.
2. Using offset
to Extract Data from a Raw Byte Array
We can extract a field at a specific byte offset in a raw byte array using the offset
parameter.
import numpy as np
# Create a raw byte array with an arbitrary structure
raw_data = np.array([ (b'X', 100, 1.5),
(b'Y', 200, 2.5),
(b'Z', 150, 3.5)],
dtype=[('char', 'S1'), ('int', np.int32), ('float', np.float64)])
# Extract the 'int' field with explicit offset from start (0 bytes)
int_field = raw_data.getfield(np.int32, offset=1)
print(int_field)
Output:
[100 200 150]
By specifying an offset
, getfield()
extracts the integer values starting from the correct memory location within the structured array.
3. Extracting Floating-Point Values from a Structured Array
Here, we extract a floating-point field from a structured array that contains multiple data types.
import numpy as np
# Define a structured array with three fields: character, integer, and floating-point
dtype = np.dtype([('char', 'S1'), ('int', np.int32), ('float', np.float64)])
data = np.array([(b'A', 10, 3.14),
(b'B', 20, 2.71),
(b'C', 30, 1.61)], dtype=dtype)
# Extract the floating-point field
float_field = data.getfield(np.float64, offset=5)
print(float_field)
Output:
[3.14 2.71 1.61]
The getfield()
method isolates the floating-point values from the structured array, producing an array of float values.