0
# Data Types and Type Operations
1
2
NumPy's flexible data type system including scalar types, structured arrays, and type conversion operations. Provides comprehensive support for handling diverse data formats and precise type control.
3
4
## Capabilities
5
6
### Core Data Type Classes
7
8
Fundamental classes for working with NumPy data types.
9
10
```python { .api }
11
class dtype:
12
"""
13
Data type object describing array element format and layout.
14
15
Parameters:
16
- obj: data type specification (str, type, dtype, etc.)
17
- align: bool, align fields to improve performance
18
- copy: bool, create copy of dtype object
19
20
Attributes:
21
- name: str, canonical name of dtype
22
- kind: str, character code for dtype category
23
- char: str, unique character code for dtype
24
- type: type, scalar type corresponding to dtype
25
- itemsize: int, size of dtype in bytes
26
- byteorder: str, byte order (endianness)
27
- fields: dict or None, field information for structured dtypes
28
- shape: tuple, shape for sub-array dtypes
29
"""
30
def __init__(self, obj, align=False, copy=False): ...
31
32
@property
33
def name(self): """Canonical name of dtype"""
34
35
@property
36
def kind(self): """Character code ('i', 'f', 'U', etc.)"""
37
38
@property
39
def itemsize(self): """Size in bytes"""
40
41
@property
42
def byteorder(self): """Byte order ('=', '<', '>', '|')"""
43
44
def astype(dtype, order='K', casting='unsafe', subok=True, copy=True):
45
"""
46
Cast array to specified type.
47
48
Parameters:
49
- dtype: str or dtype, target data type
50
- order: {'C', 'F', 'A', 'K'}, memory layout
51
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
52
- subok: bool, return subclass if possible
53
- copy: bool, force copy even if unnecessary
54
55
Returns:
56
ndarray: Array cast to new type
57
"""
58
```
59
60
### Type Information Classes
61
62
Classes providing detailed information about numeric types.
63
64
```python { .api }
65
class finfo:
66
"""
67
Machine limits for floating point types.
68
69
Parameters:
70
- dtype: floating point data type
71
72
Attributes:
73
- eps: float, difference between 1.0 and next float
74
- epsneg: float, difference between 1.0 and previous float
75
- max: float, largest representable number
76
- min: float, smallest representable positive number
77
- tiny: float, smallest positive normalized number
78
- precision: int, approximate decimal precision
79
- resolution: float, approximate decimal resolution
80
"""
81
def __init__(self, dtype): ...
82
83
@property
84
def eps(self): """Machine epsilon"""
85
86
@property
87
def max(self): """Maximum representable value"""
88
89
@property
90
def min(self): """Minimum representable positive value"""
91
92
class iinfo:
93
"""
94
Machine limits for integer types.
95
96
Parameters:
97
- dtype: integer data type
98
99
Attributes:
100
- min: int, minimum representable value
101
- max: int, maximum representable value
102
- dtype: dtype, integer data type
103
- kind: str, kind of integer ('i' or 'u')
104
- bits: int, number of bits
105
"""
106
def __init__(self, dtype): ...
107
108
@property
109
def min(self): """Minimum representable value"""
110
111
@property
112
def max(self): """Maximum representable value"""
113
114
@property
115
def bits(self): """Number of bits"""
116
```
117
118
### Type Conversion Functions
119
120
Functions for type casting and conversion operations.
121
122
```python { .api }
123
def can_cast(from_, to, casting='safe'):
124
"""
125
Returns True if cast between data types can occur according to casting rule.
126
127
Parameters:
128
- from_: data type or array, source type
129
- to: data type, target type
130
- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule
131
132
Returns:
133
bool: True if cast is possible
134
"""
135
136
def promote_types(type1, type2):
137
"""
138
Returns the data type with the smallest size and smallest scalar kind.
139
140
Parameters:
141
- type1, type2: data types to promote
142
143
Returns:
144
dtype: Promoted data type
145
"""
146
147
def result_type(*arrays_and_dtypes):
148
"""
149
Returns the type that results from applying NumPy type promotion rules.
150
151
Parameters:
152
- *arrays_and_dtypes: arrays and data types
153
154
Returns:
155
dtype: Result data type
156
"""
157
158
def min_scalar_type(a):
159
"""
160
Return the scalar dtype of minimal size and lowest kind to represent a.
161
162
Parameters:
163
- a: ndarray or scalar, input to find minimal type for
164
165
Returns:
166
dtype: Minimal scalar type
167
"""
168
169
def find_common_type(array_types, scalar_types):
170
"""
171
Determine common type following scalar-array type promotion rules.
172
173
Parameters:
174
- array_types: list of dtypes or None, array types
175
- scalar_types: list of dtypes or None, scalar types
176
177
Returns:
178
dtype: Common data type
179
"""
180
```
181
182
### Type Testing Functions
183
184
Functions to test and identify data types and array properties.
185
186
```python { .api }
187
def isscalar(element):
188
"""
189
Returns True if the type of element is a scalar type.
190
191
Parameters:
192
- element: any, input to test
193
194
Returns:
195
bool: True if element is scalar
196
"""
197
198
def issubdtype(arg1, arg2):
199
"""
200
Returns True if first argument is a typecode lower/equal in type hierarchy.
201
202
Parameters:
203
- arg1, arg2: data types to compare
204
205
Returns:
206
bool: True if arg1 is subtype of arg2
207
"""
208
209
def isdtype(obj, kind):
210
"""
211
Check if data type is of specified kind.
212
213
Parameters:
214
- obj: data type to check
215
- kind: str, kind to check against
216
217
Returns:
218
bool: True if dtype matches kind
219
"""
220
221
def isfortran(a):
222
"""
223
Check if array is Fortran contiguous but not C contiguous.
224
225
Parameters:
226
- a: ndarray, input array
227
228
Returns:
229
bool: True if Fortran contiguous
230
"""
231
232
def isreal(x):
233
"""
234
Returns a bool array, where True if input element is real.
235
236
Parameters:
237
- x: array_like, input array
238
239
Returns:
240
ndarray: Boolean array indicating real elements
241
"""
242
243
def iscomplex(x):
244
"""
245
Returns a bool array, where True if input element is complex.
246
247
Parameters:
248
- x: array_like, input array
249
250
Returns:
251
ndarray: Boolean array indicating complex elements
252
"""
253
254
def iscomplexobj(x):
255
"""
256
Check for complex number or dtype.
257
258
Parameters:
259
- x: any, input to test
260
261
Returns:
262
bool: True if x is complex type or array
263
"""
264
265
def isrealobj(x):
266
"""
267
Return True if x is not complex type or array.
268
269
Parameters:
270
- x: any, input to test
271
272
Returns:
273
bool: True if x is real type or array
274
"""
275
```
276
277
### String and Character Operations
278
279
Type conversion for string and character data.
280
281
```python { .api }
282
def typename(char):
283
"""
284
Return description for given data type code.
285
286
Parameters:
287
- char: str, data type code
288
289
Returns:
290
str: Description of data type
291
"""
292
293
def mintypecode(typechars, typeset='GDFgdf', default='d'):
294
"""
295
Return character for minimum-size type in given set.
296
297
Parameters:
298
- typechars: list of str, type codes
299
- typeset: str, set of type codes to choose from
300
- default: str, default type code
301
302
Returns:
303
str: Minimum type code
304
"""
305
```
306
307
### Structured Array Support
308
309
Support for structured arrays with named fields.
310
311
```python { .api }
312
class recarray(ndarray):
313
"""
314
Construct ndarray that allows field access using attributes.
315
316
Parameters:
317
- shape: tuple, array shape
318
- dtype: data-type, record structure
319
- buf: buffer, data buffer
320
- offset: int, buffer offset
321
- strides: tuple, memory strides
322
- formats: list, field formats (alternative to dtype)
323
- names: list, field names (alternative to dtype)
324
- titles: list, field titles
325
- byteorder: str, byte order
326
- aligned: bool, align fields
327
"""
328
def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None,
329
formats=None, names=None, titles=None, byteorder=None, aligned=False): ...
330
331
class record(void):
332
"""
333
A scalar record type for structured arrays.
334
"""
335
def __new__(subtype, obj, dtype=None, shape=None, offset=0, formats=None,
336
names=None, titles=None, byteorder=None, aligned=False): ...
337
```
338
339
### Memory Layout Classes
340
341
Classes for managing memory layout and views.
342
343
```python { .api }
344
class memmap(ndarray):
345
"""
346
Create memory-map to array stored in binary file.
347
348
Parameters:
349
- filename: str or file-like, file to map
350
- dtype: data-type, data type of array
351
- mode: str, file access mode
352
- offset: int, file offset in bytes
353
- shape: tuple, desired array shape
354
- order: {'C', 'F'}, memory layout order
355
"""
356
def __new__(subtype, filename, dtype=float, mode='r+', offset=0, shape=None, order='C'): ...
357
```
358
359
## Common NumPy Data Types
360
361
### Integer Types
362
363
```python { .api }
364
# Signed integers
365
int8 # 8-bit signed integer (-128 to 127)
366
int16 # 16-bit signed integer (-32,768 to 32,767)
367
int32 # 32-bit signed integer (-2^31 to 2^31-1)
368
int64 # 64-bit signed integer (-2^63 to 2^63-1)
369
370
# Unsigned integers
371
uint8 # 8-bit unsigned integer (0 to 255)
372
uint16 # 16-bit unsigned integer (0 to 65,535)
373
uint32 # 32-bit unsigned integer (0 to 2^32-1)
374
uint64 # 64-bit unsigned integer (0 to 2^64-1)
375
376
# Platform-dependent integers
377
int_ # Platform integer (same as C long)
378
uint # Platform unsigned integer (same as C unsigned long)
379
intp # Platform integer used for indexing
380
uintp # Platform unsigned integer used for indexing
381
```
382
383
### Floating Point Types
384
385
```python { .api }
386
float16 # 16-bit half precision float
387
float32 # 32-bit single precision float
388
float64 # 64-bit double precision float (default)
389
float_ # Platform double (same as float64)
390
391
# Extended precision (platform dependent)
392
longfloat # Extended precision float
393
float128 # 128-bit extended precision (if available)
394
```
395
396
### Complex Types
397
398
```python { .api }
399
complex64 # Complex number with float32 real and imaginary parts
400
complex128 # Complex number with float64 real and imaginary parts (default)
401
complex_ # Platform complex (same as complex128)
402
complexfloating # Base class for complex types
403
```
404
405
### String and Unicode Types
406
407
```python { .api }
408
# Fixed-length strings
409
str_ # Unicode string (same as <U)
410
bytes_ # Byte string (same as |S)
411
412
# Parameterized string types
413
'U10' # Unicode string of length 10
414
'S20' # Byte string of length 20
415
'<U5' # Little-endian Unicode string of length 5
416
```
417
418
## Usage Examples
419
420
### Basic Data Type Operations
421
422
```python
423
import numpy as np
424
425
# Create arrays with specific data types
426
int_array = np.array([1, 2, 3], dtype=np.int32)
427
float_array = np.array([1.0, 2.0, 3.0], dtype=np.float64)
428
complex_array = np.array([1+2j, 3+4j], dtype=np.complex128)
429
430
# Check data type properties
431
print(int_array.dtype) # int32
432
print(int_array.dtype.name) # int32
433
print(int_array.dtype.kind) # i (integer)
434
print(int_array.itemsize) # 4 bytes
435
436
# Type conversion
437
float_from_int = int_array.astype(np.float64)
438
int_from_float = float_array.astype(np.int32)
439
```
440
441
### Type Information and Limits
442
443
```python
444
import numpy as np
445
446
# Get information about floating point types
447
f32_info = np.finfo(np.float32)
448
print(f"Float32 precision: {f32_info.precision}")
449
print(f"Float32 max: {f32_info.max}")
450
print(f"Float32 eps: {f32_info.eps}")
451
452
# Get information about integer types
453
i32_info = np.iinfo(np.int32)
454
print(f"Int32 min: {i32_info.min}")
455
print(f"Int32 max: {i32_info.max}")
456
457
# Check casting compatibility
458
can_cast_safe = np.can_cast(np.int32, np.float64, 'safe') # True
459
can_cast_unsafe = np.can_cast(np.float64, np.int32, 'unsafe') # True
460
can_cast_safe_reverse = np.can_cast(np.float64, np.int32, 'safe') # False
461
```
462
463
### Structured Arrays
464
465
```python
466
import numpy as np
467
468
# Define structured data type
469
person_dtype = np.dtype([
470
('name', 'U20'),
471
('age', 'i4'),
472
('height', 'f4'),
473
('married', '?')
474
])
475
476
# Create structured array
477
people = np.array([
478
('Alice', 25, 165.5, True),
479
('Bob', 30, 175.0, False),
480
('Charlie', 35, 180.2, True)
481
], dtype=person_dtype)
482
483
# Access fields
484
names = people['name']
485
ages = people['age']
486
alice_age = people[0]['age']
487
488
# Create record array for attribute access
489
rec_people = np.rec.fromarrays([names, ages, people['height'], people['married']],
490
names=['name', 'age', 'height', 'married'])
491
print(rec_people.age) # Access age field as attribute
492
```
493
494
### Type Promotion and Conversion
495
496
```python
497
import numpy as np
498
499
# Automatic type promotion
500
a = np.array([1, 2, 3], dtype=np.int32)
501
b = np.array([1.0, 2.0, 3.0], dtype=np.float64)
502
result = a + b # Result is float64
503
504
# Find promoted type
505
promoted = np.promote_types(np.int32, np.float32) # float32
506
507
# Find result type for operations
508
result_type = np.result_type(np.int32, np.float64, np.complex64) # complex128
509
510
# Find minimal type for scalar
511
minimal = np.min_scalar_type(100) # int8 (smallest type that fits 100)
512
```