Está en la página 1de 13

DATA TYPE

OBJECTS (DTYPE)
Introducción
Un objeto de tipo de datos (instancia de la clase numpy.dtype) se encarga de describir como se den
interpretar los bytes en el bloque de memoria de tamaño fijo correspondiente a un elemento de matriz.
Da la descripción de los aspectos de los datos:
■ Tipo de datos (entero, flotante, objeto Python…)
■ Tamaño de los datos (cuantos bytes hay)
■ Orden de bytes de los datos (Little-endian o big -endian)
■ Si el tipo de datos es estructurado a un agregado de otros tipos de datos
1. Cuales son los nombres de los campos de la estructura, mediante los cuales se puede acceder a ellos
2. Cual es el tipo de datos de cada campo
3. Que parte del bloque de memoria ocupa cada campo
■ Si el tipo de datos es una sub matriz (sub-array) ¿Cuál es su forma y tipo de datos?
Desarrollo
Para la descripción del tipo de datos escalares integrados en el numpy, un elemento extraído del arreglo
por ejemplo mediante una indexación será un objeto Python cuyo tipo es el escalar asociado con el tipo de
datos del arreglo.
Aunque los escalares no son objetos dtype, pueden usarse en lugar de uno siempre que se necesite una
especificación de tipo de datos.
Los tipos de datos estructurados se forman creando un tipo de datos cuyo campo contiene otros de datos.
Cada campo tiene un nombre por el cual se puede acceder. El principal debe tener el tamaño suficiente
para contener todos sus campos. Los tipos de datos estructurados también pueden contener tipos de datos
de subarreglos estructurados anidados en sus campos.
Finalmente, un tipo de datos puede describir elementos que son en sí mismos conjuntos de elementos de
otro tipo de datos. Sin embargo, estas matrices secundarias deben tener un tamaño fijo.
Si se crea un arreglo utilizando un tipo de datos que describe un subarreglo, las dimensiones de este se
agregan a la forma de la matriz cuando se crea.
Ejemplos

>>> dt = np.dtype('>i4') dt = np.dtype([('name', np.unicode_, . x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0,


16), ('grades', np.float64, (2,))]) 7.0))], dtype=dt)
>>> dt.byteorder >>> x[1]
>>> dt['name']
'>' ('John', [6.0, 7.0])
dtype('|U16') >>> x[1]['grades']
>>> dt.itemsize
>>> dt['grades'] array([ 6., 7.])
4
dtype(('float64',(2,))) >>> type(x[1])
>>> dt.name <type 'numpy.void'>
'int32' >>> type(x[1]['grades'])
<type 'numpy.ndarray'>
>>> dt.type is np.int32
Elementos en un arreglo de datos que se
True envuelven en un tipo escalar con dos campos.
Especificando y construyendo tipos de datos

dtype object Usado como es se puede Array-scalar types


apreciar de la forma: ■ Los 24 objetos de tipo escalar de matriz
dtype (obj [, alinear, copiar]) Crea un incorporados se convierten en un objeto de
objeto de tipo de datos. tipo de datos asociado.

  Example

En cualquier otro caso se tiene que: >>> 

Tipo de datos predeterminado: float_ >>> dt = np.dtype(np.int32) # 32-bit integer

  >>> dt = np.dtype(np.complex128) # 128-bit


complex floating-point number
Built-in Python types
Python Array scalar
Generic types int int_
generic hierarchical type objects type objects
bool bool_
number, inexact, floating float
float float_
complexfloating cfloat complex cfloat

integer, signedinteger int_ bytes bytes_

str bytes_ (Python2)
unsignedinteger uint
or unicode_ (Python3)
character string unicode unicode_

buffer void
generic, flexible void
(all others) object_
 
Array-protocol type strings (see 
The Array Interface)
Types with .dtype El primer carácter especifica el tipo de datos y los caracteres
restantes especifican
el número de bytes por elemento, excepto para Unicode, donde se
Cualquier tipo de objeto con un atributo dtype: interpreta como el número de caracteres
se accederá al atributo y se usará directamente.
El atributo debe devolver algo que sea '?' BOOLEAN
convertible en un objeto dtype 'B' (signed) byte

Example 'B' unsigned byte


'I' (signed) integer
■ >>> 
'U' unsigned integer
■ >>> dt = np.dtype('b') # byte, native byte or- 'F' floating-point
der 'C' complex-floating point

■ >>> dt = np.dtype('>H') # big-endian un- 'M' timedelta

signed short 'M' datetime


'O' (Python) objects
■ >>> dt = np.dtype('<f') # little-endian single-
'S', 'A' zero-terminated bytes (not
precision float recommended)
'U' Unicode string
■ >>> dt = np.dtype('d') # double-precision
floating-point number 'V' raw data (void)
String with comma-separated fields
■ Arreglo separado por comas en formato básico,
Example
field named f0 containing a 32-bit integer
field named f1 containing a 2 x 3 sub-array of 64-bit floating- Type strings
point numbers
field named f2 containing a 32-bit floating-point number
■ >>> 
■ Any string in numpy.sctypeDict.keys():
■ >>> dt = np.dtype("i4, (2,3)f8, f4")
■ field named f0 containing a 3-character string
■ field named f1 containing a sub-array of shape (3,) containing
64-bit unsigned integers Example
■ field named f2 containing a 3 x 4 sub-array containing 10-
character strings
■ >>>
■ >>>  ■ >>> dt = np.dtype('uint32') # 32-bit
■ >>> dt = np.dtype("a3, 3u8, (3,4)a10") unsigned integer
 
■ >>> dt = np.dtype('Float64') # 64-bit
floating-point number
(flexible_dtype, itemsize)

El primer argumento debe ser un objeto que se convierta en


un objeto de tipo flexible de tamaño cero, el segundo
argumento es un número entero que proporciona el tamaño
de elemento deseado
Example ( fixed_dtype, shape)
>>>
Primer argumento es cualquier objeto que se pueda convertir
>>> dt = np.dtype((np.void, 10)) # 10-byte wide data en un objeto de tipo de datos de tamaño fijo. El segundo
block argumento es la forma deseada de este tipo. Si el parámetro
de forma es 1, entonces el objeto de tipo de datos es
>>> dt = np.dtype(('U', 10)) # 10-character unicode string equivalente a dtype fijo. Si la forma es una tupla, entonces el
nuevo dtype define un subconjunto de la forma dada
Example
>>>
>>> dt = np.dtype((np.int32, (2,2))) # 2 x 2 integer sub-
array
>>> dt = np.dtype(('U10', 1)) # 10-character string
>>> dt = np.dtype(('i4, (2,3)f8, f4', (2,3))) # 2 x 3 structured
sub-array
(base_dtype, new_dtype) [( field_name, field_dtype, field_shape), ...]
Permite que base_dtype se interprete como un dtype estructurado. Las
matrices creadas con este dtype tendrán dtype subyacente base_dtype
pero tendrán campos y banderas tomadas de new_dtype. Esto es útil
obj debe ser una lista de campos donde cada campo se
para crear tipos estructurados personalizados, como se hace en describe mediante una tupla de longitud 2 o. (Equivalente
matrices de registros. al elemento descrito en el atributo __array_interface__).
Este formulario también permite especificar tipos de estructura con El primer elemento, field_name, es el nombre del campo
campos superpuestos, que funcionan como el tipo "unión" en C. (si es '', se asigna un nombre de campo estándar, 'f #'). El
Example nombre del campo también puede ser una 2-tupla de
cadenas donde la primera cadena es un "título" (que
32-bit integer, whose first two bytes are interpreted as an puede ser cualquier cadena o cadena Unicode) o
integer via field real, and the following two bytes via metadatos para el campo que puede ser cualquier objeto,
field imag. y la segunda cadena es el "nombre" que debe ser un
>>> identificador válido de Python.
>>> dt = np.dtype((np.int32,{'real':(np.int16, 0),'imag': El segundo elemento, field_dtype, puede ser cualquier
(np.int16, 2)}) cosa que pueda interpretarse como un tipo de datos.
El tercer elemento opcional field_shape contiene la forma
32-bit integer, which is interpreted as consisting of a sub-
si este campo representa una matriz del tipo de datos en el
array of shape (4,) containing 8-bit integers: segundo elemento. Tenga en cuenta que una tupla de 3
>>> con un tercer argumento igual a 1 es equivalente a una
>>> dt = np.dtype((np.int32, (np.int8, 4))) tupla de 2.
Este estilo no acepta la alineación en el constructor dtype,
32-bit integer, containing fields r, g, b, a that interpret the
ya que se supone que toda la memoria se explica por la
4 bytes in the integer as four unsigned integers: descripción de la interfaz de la matriz.
>>>
>>> dt = np.dtype(('i4', [('r','u1'),('g','u1'),('b','u1'),
('a','u1')]))
Attributes
The type of the data is described by the following dtype attributes:

dtype.type The type object used Size of the data is in turn


to instantiate a
scalar of this data-
described by:
type.
dtype.kind A character code (one
of ‘biufcmMOSUV’) dtype.name A bit-width name for this
identifying the general
data-type.
kind of data.
dtype.char A unique character
dtype.itemsize The element size of this
code for each of the
data-type object.
21 different built-in
types.
dtype.num A unique number for
each of the 21
different built-in
types.
dtype.str The array-protocol Endianness of this data
typestring of this
data-type object.
dtype.byteorder A character indicating the
byte-order of this data-type
object.
Information about sub-data-types in a 
structured data type:
dtype.fields
Dictionary of named fields defined for
this data type, or None.
dtype.names Ordered list of field names, or None if
there are no fields.

Attributes providing
additional information:
For data types that describe sub-arrays:
dtype.hasobject Boolean indicating whether this
dtype contains any reference-
counted objects in any fields or sub-
dtype.subdtype dtypes.
Tuple (item_dtype, shape) if this 
dtype describes a sub-array, and
dtype.flags Bit-flags describing how this data type
None otherwise. is to be interpreted.
dtype.shape Shape tuple of the sub-array if this
dtype.isbuiltin Integer indicating how this dtype
data type describes a sub-array,
relates to the built-in dtypes.
and () otherwise.
dtype.isnative Boolean indicating whether the byte
order of this dtype is native to the
platform.

dtype.descr __array_interface__ description of the


data-type.
dtype.alignment The required alignment (bytes) of this
data-type according to the compiler.
Methods
1° Data types have the following method for
dtype.newbyteorder([new_order])
Return a new dtype with a different changing the byte order:
byte order.
2°The following methods implement the pickle
protocol:

dtype.__reduce__() Helper for pickle.

dtype.__setstate__()

También podría gustarte