Search results
Example. A structured data type containing a 16-character string (in field ‘name’) and a sub-array of two 64-bit floating-point number (in field ‘grades’): >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt['name'] dtype('<U16') >>> dt['grades'] dtype(('<f8', (2,)))
- Ndarray
The type of items in the array is specified by a separate...
- The Array Interface Protocol
Note. This page describes the NumPy-specific API for...
- Iterating Over Arrays
Modifying array values#. By default, the nditer treats the...
- Standard Array Subclasses
Note. If you define __array_ufunc__:. If you are not a...
- Masked Arrays
NumPy’s module structure; Array objects. The N-dimensional...
- Datetimes and Timedeltas
Datetime and timedelta arithmetic#. NumPy allows the...
- Structured Arrays
Casts a structured array to a new dtype using assignment by...
- Ndarray
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string: In [1]: float_formatter = "{:.2f}".format.
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.
25 lut 2024 · Knowing the dtype of your NumPy array is critical for performing efficient numeric computations and data analysis in Python. Example 1: Basic Usage of dtype. import numpy as np. # Create an integer array . arr = np.array([1, 2, 3, 4]) print("Array's dtype:", arr.dtype) # Output: Array's dtype: int64.
Once you have imported NumPy using import numpy as np you can create arrays with a specified dtype using the scalar types in the numpy top-level API, e.g. numpy.bool, numpy.float32, etc. These scalar types as arguments to the dtype keyword that many numpy functions or methods accept.
Example. A record data type containing a 16-character string (in field ‘name’) and a sub-array of two 64-bit floating-point number (in field ‘grades’): >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt['name'] dtype('|S16') >>> dt['grades'] dtype(('float64',(2,)))
The handy thing with structured arrays is that you can now refer to values either by index or by name: In [6]: # Get all names data['name'] Out [6]: array(['Alice', 'Bob', 'Cathy', 'Doug'], . dtype='<U10') In [7]: # Get first row of data data[0] Out [7]: ('Alice', 25, 55.0) In [8]: