Academia Master Trader

Laboratórios de leitura de gráficos e conceitos financeiros. Projeto educacional brasileiro. Exemplos fictícios, sem recomendação de investimento.

NumPy isnat identifica NaT en fechas y duraciones sin decidir cómo completar el calendario

Una columna temporal puede contener una fecha registrada y otra entrada sin tiempo definido. Antes de ordenar, agrupar o calcular intervalos, conviene identificar esa diferencia. NumPy ofrece isnat para reconocer NaT, el marcador temporal cuyo nombre significa not a time. Academia Master Trader presenta esta explicación en español para lectores de Guyana.

La función trabaja con datos de fecha o duración de NumPy. Su respuesta indica dónde aparece NaT, pero no explica por qué falta ese dato ni elige un reemplazo.

Una respuesta por cada entrada temporal

Después de import numpy as np, defina fechas = np.array(['2026-01-01','NaT','2026-01-03'],dtype='datetime64[D]').

La expresión np.isnat(fechas) devuelve el arreglo booleano [False, True, False]. Solo la posición central contiene el marcador temporal.

Las fechas del ejemplo son valores ilustrativos. La unidad D indica días en el dtype; la máscara conserva la correspondencia con las posiciones de entrada.

Para una entrada escalar, el resultado también es escalar. Por ejemplo, np.isnat(np.datetime64('NaT','D')) devuelve True. No es necesario crear primero una columna para consultar un único valor temporal.

Correspondencia entre tres fechas y su máscara NaT

Una duración cero no es una duración ausente

El mismo concepto se aplica al dtype timedelta64. Defina duraciones = np.array([0,'NaT',2],dtype='timedelta64[D]'). La llamada np.isnat(duraciones) produce otra vez [False, True, False].

Cero días es una duración registrada, aunque su magnitud sea cero. NaT representa una situación distinta. Reemplazar todas las ausencias por cero mezclaría esas dos interpretaciones sin que la función lo haya pedido.

La máscara ayuda a mantener visible esa separación. La decisión posterior depende de lo que cada fila significa dentro del conjunto de datos.

Reconocer un marcador no valida toda la columna

Un resultado False significa que esa entrada no es NaT. No demuestra que la fecha pertenezca al período esperado, que las filas estén ordenadas o que una duración respete las reglas del proceso.

Tampoco debe usarse isnat como un clasificador general de cualquier texto vacío, número o etiqueta. La entrada prevista tiene dtype temporal datetime64 o timedelta64. Convertir una fuente textual en datos temporales es un paso diferente.

Mantenga separadas la lectura de la fuente, su conversión y la identificación del marcador. Así puede explicar en qué etapa se originó cada decisión.

Conservar el significado de las posiciones

Guarde la máscara junto a la referencia de las filas que describe. Si más tarde ordena o filtra los datos, mantenga alineadas las fechas y sus identificadores.

Antes de completar una ausencia, determine qué información puede sostener ese reemplazo. isnat señala una propiedad concreta del valor; no inventa la fecha que falta ni reconstruye acontecimientos.

Continúe aprendiendo con Academia Master Trader en academiamastertrader.com.br y en Aprenda. Una máscara temporal resulta más útil cuando cada posición conserva su significado.

NumPy array2string prepara una vista textual del arreglo, no una copia completa para guardar

Una vista abreviada puede ser útil al explicar una secuencia, pero no debe confundirse con todos sus datos. NumPy ofrece array2string para construir una representación textual de un arreglo con opciones de separación, precisión y resumen. Academia Master Trader presenta esta explicación en español para lectores de Canadá.

La función devuelve una cadena. El arreglo de entrada conserva sus valores y su forma, aunque el texto muestre menos cifras o sustituya una parte de los elementos por puntos suspensivos.

Elegir entre una vista completa y un resumen

Después de import numpy as np, defina a = np.arange(8). El arreglo contiene los enteros del cero al siete.

La llamada np.array2string(a,separator=', ',threshold=5,edgeitems=2) produce el texto [0, 1, ..., 6, 7]. El tamaño total supera el umbral indicado y la vista conserva dos elementos de cada extremo de esta dimensión.

Los puntos suspensivos no son un valor del arreglo. Representan una sección que no aparece en esa vista textual.

Con np.array2string(a,separator=', ',threshold=8,edgeitems=2), la salida es [0, 1, 2, 3, 4, 5, 6, 7]. En este ejemplo, el número de elementos ya no supera el umbral y se muestran todos.

Un mismo arreglo con dos umbrales de representación

Menos cifras visibles no cambian los valores

Defina x = np.array([1.234,5.678]). La expresión np.array2string(x,precision=1,floatmode='fixed',separator=', ') devuelve [1.2, 5.7] como cadena.

Ese texto muestra una cifra después del punto decimal. No reemplaza dentro de x los valores originales por los números abreviados de la pantalla.

El modo fixed hace explícito cómo interpretar precision. Otros modos tienen reglas distintas; por ejemplo, unique busca la cantidad mínima de cifras que identifique cada valor y no utiliza precision de la misma manera.

Cuando una figura o un informe muestra números abreviados, indique la regla visual empleada. Así el lector distingue los valores guardados de la forma elegida para presentarlos.

El separador no convierte la salida en un formato de intercambio

Usar una coma entre elementos facilita ciertas lecturas, pero no convierte automáticamente esta representación en un archivo de datos completo y reutilizable.

Un resumen puede omitir entradas, la presentación puede abreviar cifras y los arreglos multidimensionales pueden introducir saltos de línea. Esas decisiones sirven a la lectura humana, no garantizan una recuperación íntegra de los datos originales.

Documentar las opciones que importan

Para que una explicación sea clara, establezca las opciones relevantes en la llamada en vez de depender de una configuración de impresión que el lector desconoce.

Revise el texto que realmente se produjo y conserve aparte el arreglo original cuando necesite seguir calculando. Una cadena legible y un conjunto de datos completo cumplen funciones distintas.

Continúe aprendiendo con Academia Master Trader en academiamastertrader.com.br y en Aprenda. Una buena presentación explica lo que muestra y también deja claro cuándo está resumiendo.

NumPy geterr consulta la política de avisos numéricos, no la calidad de los datos

Un cálculo puede producir un aviso en un entorno y continuar silenciosamente en otro. Antes de interpretar esa diferencia, conviene conocer la configuración que NumPy utiliza para manejar determinadas excepciones de punto flotante. Academia Master Trader presenta esta explicación en español para lectores de Belice.

La función np.geterr() devuelve la política actual. No ejecuta el cálculo que le interesa, no recorre un arreglo y no modifica por sí misma la configuración.

Un diccionario con cuatro entradas

Después de import numpy as np, puede guardar la consulta con politica = np.geterr(). El resultado es un diccionario con las claves divide, over, under e invalid.

En una sesión con la configuración mostrada en la documentación, el resultado es {'divide':'warn','over':'warn','under':'ignore','invalid':'warn'}. Esta es una configuración ilustrativa, no una respuesta que deba suponerse idéntica en todos los programas.

La clave divide corresponde a división por cero. La clave over identifica desbordamiento, under identifica subdesbordamiento e invalid corresponde a operaciones numéricas no válidas. Cada entrada indica cómo se atiende esa categoría.

Cuatro categorías consultadas por geterr

Interpretar el modo sin confundirlo con un resultado

Los modos posibles son ignore, warn, raise, call, print y log. Describen respuestas distintas: omitir la notificación, emitir un aviso, lanzar una excepción, llamar una función configurada, imprimir un mensaje o registrar mediante un objeto preparado para ello.

Por ejemplo, politica['invalid'] permite leer el modo asociado a la categoría invalid. Si devuelve warn, eso describe el tratamiento configurado; no afirma que ya haya ocurrido una operación inválida.

La consulta tampoco informa cuántas veces apareció una categoría durante la ejecución. Un diccionario de configuración no es un historial de eventos ni un resumen de valores ausentes.

El silencio no valida un arreglo

Que una categoría tenga el modo ignore no significa que todos los valores sean finitos o apropiados para el análisis. Significa que esa categoría se maneja con ese modo de notificación.

Asimismo, ver warn no demuestra que un cálculo haya fallado. Para interpretar una ejecución concreta hay que revisar la operación realizada, sus entradas y los resultados que produjo.

Mantenga separadas tres preguntas: qué política está activa, qué ocurrió durante el cálculo y si los datos obtenidos cumplen el requisito de su trabajo. geterr responde a la primera.

Una consulta útil al documentar una ejecución

Si prepara un ejemplo reproducible, puede registrar la política junto con la versión de NumPy y los pasos del cálculo. Así queda explícita una parte del entorno que influye en los avisos observados.

Lea de nuevo la configuración en el contexto donde importa, en lugar de copiar una salida antigua como si describiera cualquier sesión futura. Consultar es distinto de cambiar: modificar la política requiere una acción aparte.

Continúe aprendiendo con Academia Master Trader en academiamastertrader.com.br y en Aprenda. Describir el entorno con precisión ayuda a explicar un resultado sin atribuir a la configuración propiedades que no comprueba.

NumPy promote_types elige un dtype común sin convertir los datos

Al combinar fuentes numéricas, una decisión importante es el tipo de dato que podrá representar los tipos de entrada. NumPy ofrece promote_types para consultar esa decisión a partir de dos descripciones de dtype. La función devuelve otro dtype, no un arreglo convertido.

Para lectores de habla hispana en Estados Unidos, esta distinción permite separar dos pasos de una preparación de datos: definir la representación común y después decidir cómo crear o convertir los arreglos que la utilizarán.

Una consulta entre dos tipos

Después de import numpy as np, la expresión np.promote_types('int16','float32') devuelve dtype('float32'). En este par, el tipo flotante de 32 bits es el resultado de la promoción.

En cambio, np.promote_types('int64','float32') devuelve dtype('float64'). No basta con observar que una entrada ya es flotante y mantener automáticamente su anchura.

La consulta utiliza los tipos indicados, no el valor concreto almacenado en una observación. Aunque hoy todos los enteros de una columna sean pequeños, describirla como int64 sigue proporcionando a la función ese dtype completo.

Dos consultas de promoción con resultados distintos

El signo también cambia el resultado

La llamada np.promote_types('int8','uint8') devuelve dtype('int16'). Un entero de ocho bits con signo y otro de ocho bits sin signo no cubren el mismo intervalo.

El resultado muestra por qué elegir simplemente uno de los tipos originales puede ser insuficiente. La promoción considera ambos tipos y puede devolver una representación distinta de las dos entradas.

Con np.promote_types('float32','float64'), el resultado es dtype('float64'). Conviene escribir los tipos explícitamente cuando la anchura forma parte del contrato de los datos.

Consultar no es transformar

Obtener un dtype común no modifica los arreglos existentes, no rellena valores ausentes y no revisa las unidades de una columna. Dos series pueden compartir representación numérica y seguir describiendo cantidades diferentes.

Tampoco debe interpretarse la promoción como una garantía general de exactitud matemática para todos los enteros grandes al pasar a punto flotante. La política de promoción de NumPy y la representación exacta de cada valor son cuestiones que deben distinguirse.

La documentación indica que el resultado es canónico y utiliza el orden nativo de bytes. También señala que la operación es simétrica, pero rara vez asociativa: intercambiar las dos entradas conserva el resultado, mientras que agrupar una cadena de promociones de otra manera puede cambiarlo.

Documentar la decisión completa

Registre los dtypes de entrada y el dtype obtenido. Si después convierte un arreglo, trate esa conversión como un paso separado y revise sus requisitos de precisión y significado.

Continúe aprendiendo con Academia Master Trader en academiamastertrader.com.br y en Aprenda. Una representación común es una decisión técnica concreta, no un sustituto de conocer los datos.

NumPy iterable checks whether an object can be traversed, not whether it contains usable numbers

A list, a string and an empty container can all be iterable, even though they play different roles in a numerical workflow. Academia Master Trader presents this English lesson for readers in Mexico, using NumPy iterable to distinguish the ability to traverse an object from assumptions about its contents, size or suitability for a calculation.

Begin with an ordinary sequence

After import numpy as np, the call np.iterable([1,2,3]) returns True. A list supports traversal through its entries.

By contrast, np.iterable(2) returns False. The integer two is a scalar object rather than a sequence to traverse.

The function returns one Boolean about the supplied object. It does not calculate a summary, convert the input into an array or return a separate answer for every entry inside it.

Use it when the actual question is whether iteration is supported. Other requirements need their own explicit checks.

Iterability does not establish numeric contents or a nonempty sequence

A zero-dimensional array is an important distinction

Define a = np.array(1.0). Although this is a NumPy array, np.iterable(a) returns False because the array is zero-dimensional.

A one-dimensional array containing a single value is different. The call np.iterable(np.array([1.0])) returns True.

The number of stored values alone does not settle the question. The dimensional form of the array matters.

NumPy's documentation also notes a difference from isinstance(a,Iterable) after from collections.abc import Iterable. For the zero-dimensional array, that classification returns True while np.iterable returns False.

Do not substitute one expression for the other without considering this case in the input contract.

True says nothing about numeric contents

The call np.iterable('abc') returns True. Iterating over a string yields characters, not a sequence of numerical observations.

An empty list is iterable too: np.iterable([]) returns True. The answer does not establish that at least one entry exists.

A dictionary can also be traversed. Under ordinary dictionary iteration, its keys are yielded, so treating any iterable as a list of numeric values can introduce a separate mistake about meaning.

These examples are not exceptions to the function's purpose. They illustrate how broad the property of iterability is.

Keep the data contract separate

A calculation may require a nonempty, one-dimensional sequence of finite numeric observations. Iterability alone establishes none of those additional conditions.

State the required form, then inspect shape, contents and any value properties that matter to the calculation. A readable acceptance rule is clearer than relying on one broad classification to do several jobs.

When an input is iterable, also decide what one iteration is supposed to represent. Rows of a matrix, characters of a label and keys of a mapping are different units of work.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Ask whether traversal is supported, then separately ask whether the traversed objects are the data you intended.

NumPy format_float_scientific controls a floating-point display without adding measurement precision

Scientific notation separates a coefficient from a power of ten, making very large or small values easier to label. Formatting that label is different from improving the underlying data. Academia Master Trader presents this English lesson for readers in Cuba, using NumPy format_float_scientific to distinguish stored values, generated digits and presentation choices.

The output is a string

After import numpy as np, the call np.format_float_scientific(1250.0) returns '1.25e+03'.

The coefficient 1.25 multiplied by ten to the third power describes the original value. The returned object is text intended for a label, report or another explicitly defined textual format.

It is not a new numerical dtype or a more accurate copy of the input. Keep the numeric object for calculations and format a separate string for display.

The function accepts a Python float or a NumPy floating-point scalar. It is a scalar formatter rather than an array-wide computation.

Scientific formatting separates coefficient digits, trimming and exponent padding

An explicit precision changes the displayed coefficient

The call np.format_float_scientific(1250.0,unique=False,precision=3) returns '1.250e+03'.

Here the coefficient has three digits after the decimal point. Including that final zero is a presentation choice under the selected formatting options.

When unique is False, precision must be an integer. This mode generates digits as if printing an infinite-precision value and rounds when it stops, as NumPy's documentation describes.

Do not interpret the added zero as evidence that an instrument or source measured the value more accurately. A formatter cannot supply missing information about measurement quality.

Trimming and exponent padding are separate controls

Adding trim='-' to the preceding call produces '1.25e+03'. This option removes trailing coefficient zeros and any trailing decimal point.

By contrast, exp_digits controls the exponent's minimum digit count. It does not request extra meaningful digits in the coefficient.

For example, np.format_float_scientific(1250.0,unique=False,precision=3,sign=True,exp_digits=4) returns '+1.250e+0003'.

The positive sign and padded exponent may help align a consistent display. They do not alter the represented value.

More printed digits can expose the stored approximation

NumPy documents s = np.float32(1.23e24). The ordinary scientific representation is '1.23e+24'.

With unique=False and precision=15, the documented output is '1.230000071797338e+24'. Those extra digits describe the stored floating-point approximation rather than newly recovered decimal accuracy.

The default unique strategy seeks a short representation that identifies the floating-point value among values of the same type. Supplying a smaller precision can limit the printed digits, so a short label should not be treated as a complete storage record automatically.

Choose display rules for the audience and purpose, while keeping the original values and their dtype available wherever numerical fidelity matters.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Separate a readable label from a claim about the precision of its source.

NumPy real_if_close converts a complex array only when every imaginary part is close to zero

A calculation can produce complex values whose imaginary components are very small. Deciding whether to discard those components needs an explicit rule. Academia Master Trader presents this English lesson for readers in Nicaragua, using NumPy real_if_close to explain an array-wide conversion based on a stated tolerance rather than an automatic declaration that imaginary values are meaningless.

The decision concerns the whole array

After import numpy as np, define a = np.array([2+0.001j,5+0.002j]).

The call np.real_if_close(a,tol=0.01) returns a floating-point array containing 2.0 and 5.0. Both imaginary components are within the selected closeness rule.

Now define b = np.array([2+0.001j,5+0.2j]). With the same tolerance, np.real_if_close(b,tol=0.01) keeps a complex array.

The second component prevents conversion of the array as a whole. The first entry does not receive a separate real dtype while the second remains complex.

This is a conditional conversion, not an element-by-element Boolean mask.

All imaginary components must satisfy the rule before the complex array becomes real

Tolerance has two interpretations

The default tolerance is 100. For tolerance values greater than one, the threshold is the tolerance multiplied by machine epsilon for the relevant floating-point type.

Machine epsilon describes the spacing associated with that type near one. A tolerance of 100 therefore does not mean an imaginary component of one hundred is acceptable.

When the supplied tolerance is at most one, NumPy uses it as an absolute tolerance instead. The earlier value 0.01 uses this branch.

These interpretations make the parameter's scale important. State which interpretation applies before choosing a number for a workflow.

The documented examples show the boundary's effect

NumPy documents the input [2.1+4e-14j,5.2+3e-15j] with tol=1000. On the documented floating-point setting, the result is a real array containing 2.1 and 5.2.

Increasing the first imaginary component to 4e-13j keeps the result complex under the same setting.

The threshold comes from the imaginary components and the floating-point type. It is not a percentage of each entry's real component.

Avoid relying on a value exactly at a threshold in an explanation. Values clearly on either side make the intended distinction easier to inspect.

Conversion requires a reason beyond smallness

A small imaginary component may be numerical residue, or it may carry information that matters to the application. The function does not decide which interpretation is scientifically appropriate.

Choose the rule from the calculation's meaning and required accuracy. Keep the complex result when the reason for discarding its imaginary part has not been established.

If conversion occurs, later code receives a real-valued array. Check that downstream expectations match that possible change in dtype.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the tolerance and its interpretation whenever a complex-to-real conversion affects the result.

NumPy base_repr writes an integer in another base without changing its value

The text 101 can mean different quantities depending on the base used to read it. A base label is part of the meaning, not decoration. Academia Master Trader presents this English lesson for readers in El Salvador, using NumPy base_repr to separate an integer's value from the string chosen to represent it.

Begin with the default binary representation

After import numpy as np, the call np.base_repr(5) returns the string '101'.

The default base is two. Reading those digits in binary gives one group of four, no groups of two and one unit, totaling five.

The function has not changed five into the decimal integer one hundred and one. It has produced text that represents five in a different positional number system.

That distinction matters when writing labels, exporting data or comparing a displayed representation with a value used in arithmetic.

The same integer can have different digit strings in different bases

A different base changes the digit positions

The call np.base_repr(6,base=5) returns '11'. In base five, the left digit contributes five and the right digit contributes one.

Likewise, np.base_repr(32,base=16) returns '20'. Two groups of sixteen and zero units describe the original decimal value thirty-two.

Each position has a weight determined by the base. Reading the output correctly requires keeping that base with the text.

The supported base range is two through thirty-six. Above base ten, letter symbols extend the available digits. For example, np.base_repr(10,base=16) returns 'A', and np.base_repr(35,base=36) returns 'Z'.

Padding adds zeros rather than setting a final width

NumPy's example np.base_repr(7,base=5,padding=3) returns '00012'.

Without padding, seven in base five is written as 12. The padding argument adds three zeros to the left of that representation.

It does not mean that the finished output must contain exactly three characters. In this example, the resulting string contains five digit characters.

Use that distinction when aligning labels. A request for a fixed overall field width is a different formatting rule from a request to add a specified number of zeros.

Negative output is signed text

The call np.base_repr(-5) returns '-101'. The leading minus sign accompanies a binary representation of the magnitude.

Do not interpret that string as a fixed-width two's-complement bit pattern. The function's output here is a signed textual representation, not a specification of machine storage.

The input parameter is an integer. The result is a string, so concatenating it with another string joins characters rather than adding numeric values.

Keep the original integer for calculations and use the representation for display or an explicitly defined text format.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Label the base whenever a digit string could otherwise be read ambiguously.

NumPy isscalar asks about scalar types, not whether an input is one number

A string can receive True from NumPy isscalar, while a zero-dimensional array containing a number receives False. That contrast is useful when designing an input rule. Academia Master Trader presents this English lesson for readers in Honduras, separating scalar type, array dimensionality and numerical suitability instead of treating them as the same question.

A direct scalar example

After import numpy as np, the call np.isscalar(3.1) returns True. The input is a Python floating-point scalar.

A NumPy floating-point scalar also qualifies. For example, np.isscalar(np.float64(3.1)) returns True.

The result is one Boolean describing the supplied object. The function does not convert it into an array, compute its shape or return a Boolean for each entry inside a container.

Start by deciding whether a type classification is actually what the application needs. A rule about individual measurements may require different evidence from a rule about accepted input forms.

Scalar type and zero-dimensional shape are different questions

A zero-dimensional array is still an array

Define a = np.array(3.1). This object has zero dimensions, but np.isscalar(a) returns False.

The distinction is not about how many numeric values the object contains. It is about the kind of object being supplied.

For comparison, np.ndim(a) == 0 returns True. NumPy's documentation recommends the dimensionality expression in most cases where zero-dimensional arrays should be accepted alongside scalars.

That expression answers a different question. Choosing it should reflect the intended input contract, rather than an attempt to make both functions produce identical answers.

A one-element list is different again. The call np.isscalar([3.1]) returns False, and its dimensionality is one rather than zero.

True does not establish numerical suitability

The call np.isscalar('numpy') returns True. Built-in strings are among the types treated as scalar by this function.

Likewise, np.isscalar(False) returns True. A Boolean belongs to the accepted scalar types even when an application would not accept it as a measurement.

These examples show why a True result is not proof that an input can be used in every numerical operation.

For a stricter numerical scalar classification, the documentation points to isinstance(x,numbers.Number) after importing the numbers module. Even that classification should be matched to the application's policy, including its treatment of Boolean values.

Write the acceptance rule first

An input rule might accept numeric scalars, allow zero-dimensional numeric arrays, or require a sequence of observations. Those are separate contracts.

After choosing one, check type, dimensionality and any required value properties explicitly. Do not let the convenient name isscalar silently decide all of them.

Keeping these questions separate also makes error messages more useful: an unexpected container is a different issue from an accepted shape containing unsuitable data.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Use scalar classification only for the question it actually answers.

NumPy min_scalar_type describes a compact scalar dtype, not an array compression plan

A small number and an array containing that number do not necessarily receive the same answer from NumPy min_scalar_type. The input form matters. Academia Master Trader presents this English lesson for readers in the Dominican Republic, showing how the function describes scalar values while leaving the dtype of a non-scalar array unchanged.

Start with the scalar value

After import numpy as np, the call np.min_scalar_type(10) returns dtype('uint8').

The positive integer ten fits in an eight-bit unsigned integer. For this scalar, NumPy selects a compact dtype from the smallest applicable scalar kind and size.

A negative example changes the answer: np.min_scalar_type(-260) returns dtype('int16'). An unsigned integer cannot represent that negative value, and an eight-bit signed integer does not have enough range.

The output is a dtype object. It is not an array, a converted scalar or a measurement of the memory occupied by the original Python object.

Scalar inputs receive compact dtype descriptions while a one-element array keeps its existing dtype

Floating values remain floating

The call np.min_scalar_type(2.0) returns dtype('float16'), rather than an integer dtype.

Even though two has no fractional part here, the function does not demote floating-point values to integers. Likewise, complex scalar values are not demoted to floating-point values.

For example, np.min_scalar_type(2+0j) returns dtype('complex64'). A zero imaginary component does not make this function choose a real-valued dtype.

These rules preserve the scalar kind boundary. They are important when interpreting the word smallest: it does not mean searching every numeric kind for the shortest possible storage of a mathematically equivalent number.

Range is not a promise of identical decimal precision

NumPy's documented example np.min_scalar_type(3.1) returns dtype('float16'). Another example, np.min_scalar_type(1e50), returns dtype('float64').

Do not read the first answer as a promise that a conversion will preserve every digit or give an exact decimal representation of 3.1.

If a workflow has a precision requirement, describe and check that requirement separately. A compact dtype suggestion is not a substitute for a numerical accuracy policy.

A non-scalar array keeps its dtype

Define a = np.array([10],dtype=np.int64). Calling np.min_scalar_type(a) returns dtype('int64').

The function does not scan this array and recommend uint8 merely because its one stored entry is small. For a non-scalar array, it returns the existing dtype unchanged.

The distinction also explains why using the scalar ten in one call and a one-element array in another can produce different results without either answer being inconsistent.

To design an array conversion, consider the complete data range, required precision and later operations. Perform any conversion as a separate, explicit step.

Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Identify the input form before turning a dtype description into a storage decision.