Python astype int numpy

Функция Numpy astype() в Python: преобразование типов

Numpy astype() — это функция приведения типов данных в Python. Чтобы преобразовать один из типов в int или один из других типов в numpy, используйте метод numpy astype().

Numpy float в массив int

Чтобы преобразовать numpy float в массив int в Python, используйте функцию np.astype(). np.astype() — это библиотечная функция numpy, которая принимает массив значений с плавающей запятой и преобразует его в целочисленный массив.

Давайте конвертировать шаг за шагом.

Шаг 1: Создайте массив numpy

Шаг 2: Преобразуйте Numpy float в int, используя numpy.astype()

Преобразуем массив с плавающей запятой в массив int.

Из вывода видно, что все значения преобразованы в целочисленные значения.

Теперь мы проверим dtype данного объекта массива.

Мы видим, что тип данных преобразованного массива — целое число.

Преобразование массива с плавающей запятой Numpy в int с помощью функции np.int_()

Numpy int_() — это тип Python, представляющий скалярный тип NumPy.

Здесь мы получим тот же результат, но другим методом.

Но я предлагаю использовать функцию numpy astype(), которая может преобразовывать стандартные типы данных.

Numpy astype() с np.inf() и np.nan()

В нашем исходном массиве некоторые значения являются не плавающими, а значениями np.inf или np.nan.

Из вывода видно, что результаты неожиданны. Таким образом, вы должны быть осторожны при преобразовании всех значений массива в другой тип данных.

Numpy nan и numpy inf являются значениями с плавающей запятой и не могут быть осмысленно преобразованы в int.

Преобразование массива Numpy в комплексное число

Функция Numpy astype() может преобразовывать любой тип данных в другой. Однако он не обязательно преобразуется в определенные типы данных.

Давайте преобразуем тип данных float в тип «complex128», используя numpy.astype().

Источник

numpy.ndarray.astype#

Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.

Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.

  • ‘no’ means the data types should not be cast at all.
  • ‘equiv’ means only byte-order changes are allowed.
  • ‘safe’ means only casts which can preserve values are allowed.
  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • ‘unsafe’ means any data conversions may be done.

If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.

copy bool, optional

By default, astype always returns a newly allocated array. If this is set to false, and the dtype , order, and subok requirements are satisfied, the input array is returned instead of a copy.

Returns : arr_t ndarray

Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype , order.

When casting from complex to float or int. To avoid this, one should use a.real.astype(t) .

Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.

Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.

>>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5]) 

Источник

numpy.ndarray.astype#

Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.

Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.

  • ‘no’ means the data types should not be cast at all.
  • ‘equiv’ means only byte-order changes are allowed.
  • ‘safe’ means only casts which can preserve values are allowed.
  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • ‘unsafe’ means any data conversions may be done.

If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.

copy bool, optional

By default, astype always returns a newly allocated array. If this is set to false, and the dtype , order, and subok requirements are satisfied, the input array is returned instead of a copy.

Returns : arr_t ndarray

Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype , order.

When casting from complex to float or int. To avoid this, one should use a.real.astype(t) .

Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.

Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.

>>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5]) 

Источник

NumPy Astype

NumPy” is a powerful numerical computing library in Python that is capable of handling large, multidimensional arrays and matrices. The “numpy.astype()” function is an incredibly useful feature that lets you easily convert the data type of a NumPy array to another data type.

In this article, we will provide an in-depth guide on the “numpy.astype()” function using numerous examples. Here are the contents of this Python blog:

What is the “numpy.astype()” Function in Python?

The “numpy.astype()” function is utilized to change the datatype of a NumPy array and returns a new array with the particular data type keeping the original array unchanged.

  • The “dtype” parameter specifies the new data type of the array. It can be a string (e.g., int, float, str, etc) or a NumPy data type object (e.g., np.int32, np.float64, np.str).
  • The optional parameter “order” specifies the memory layout of the output array.
  • The optional parameter “casting” specifies the type of casting rule to use. The default is “unsafe”.
  • The optional partner “subok” indicates whether to retrieve a subclass of the given array if possible. When set to “True”, a subclass is returned if it is possible.
  • The optional parameter “copy” determines whether to generate a new copy of the original array. It is set by default to “True”, causing a new copy to be created.

Example 1: Applying thenumpy.astype()Function to Convert an Array of Float Type to an Integer Type

This example converts the given array of float elements into integer type using the “numpy.astype()” function:

import numpy
arr = numpy.array ( [ 1.2 , 2.4 , 3.6 , 4.8 ] )
new_arr = arr.astype ( int )
print ( «Original array:» , arr )
print ( «New array:» , new_arr )

  • The “array()” function is used to create an array of float-type elements.
  • After that, the “astype()” function takes the integer as an argument and converts the original array to an integer type, thereby transforming the “float” array values into “int”.

In the above output, the original array of floating-point numbers has been converted into the integer type successfully.

Example 2: Applying thenumpy.astype()Function to Convert an Array of Float Type to Boolean Type

This example converts the initialized array of “int” type into “boolean”. Here is an example code:

import numpy
arr = numpy.array ( [ 1 , 2 , 3 , 4 ] )
new_arr = arr.astype ( bool )
print ( «Original array:» , arr )
print ( «New array:» , new_arr )

  • Likewise, the “array()” function is used to create an array with integer numbers.
  • The “astype()” function is used to convert the “int” array into a “boolean” data type by taking the “bool” specifier as its argument.

In the above output, the original array of integers has been converted into the boolean type accordingly.

Example 3: Applying thenumpy.astype()Function to Convert an Array of Integer Type to Complex Type

This example transforms the array of “int” type into a complex type via the “numpy.astype()” function:

import numpy
arr = numpy.array ( [ 1 , 2 , 3 , 4 ] )
new_arr = arr.astype ( complex )
print ( «Original array:» , arr )
print ( «New array:» , new_arr )

In the above code snippet:

  • Similarly, the “array()” function is used to create an array of integers type values.
  • The “astype()” function is used to convert the given array into a “complex” type by accepting the complex specifier as its argument.

In the above outcome, it can be implied that the complex array has been created from the original array of integers.

Example 4: Applying thenumpy.astype()Function to Convert an Array of Integer Type to String Type

The following example converts the array values comprising the “int” type into “string” using the “numpy.astype()” function:

import numpy
arr = numpy.array ( [ 1 , 2 , 3 , 4 ] )
new_arr = arr.astype ( str )
print ( «Original array:» , arr )
print ( «New array:» , new_arr )

  • Recall the discussed approach for creating array integers.
  • Now, apply the “astype()” function that takes the “str” specifier as its argument and converts the “int” type array into a string.

As observed, a “string” array has been retrieved from the original array of integers appropriately.

Conclusion

The “astype()” function of the “numpy” library is used to change the data type of a NumPy array into other data types such as “str”, “int”, “complex”, etc. We can modify a NumPy array from a float data type to an int, object, or complex type. This blog discussed a detailed explanation and example of the “numpy.astype()” function.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.

Источник

Читайте также:  Python tmp file names
Оцените статью