NumPy Data Types

Python 中的数据类型

默认情况下,Python 拥有以下数据类型:

  • strings - 用于表示文本数据,文本用引号引起来。例如 "ABCD"。
  • integer - 用于表示整数。例如 -1, -2, -3。
  • float - 用于表示实数。例如 1.2, 42.42。
  • boolean - 用于表示 True 或 False。
  • complex - 用于表示复平面中的数字。例如 1.0 + 2.0j,1.5 + 2.5j。

NumPy 中的数据类型

NumPy 有一些额外的数据类型,并通过一个字符引用数据类型,例如 i 代表整数,u 代表无符号整数等。

以下是 NumPy 中所有数据类型的列表以及用于表示它们的字符。

  • i - 整数
  • b - 布尔
  • u - 无符号整数
  • f - 浮点
  • c - 复合浮点数
  • m - timedelta
  • M - datetime
  • O - 对象
  • S - 字符串
  • U - unicode 字符串
  • V - 固定的其他类型的内存块 ( void )

检查数组的数据类型

NumPy 数组对象有一个名为 dtype 的属性,该属性返回数组的数据类型:

Instance

获取数组对象的数据类型:

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)

Run Instance

Instance

获取包含字符串的数组的数据类型:

import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)

Run Instance

用已定义的数据类型创建数组

我们使用 array() 函数来创建数组,该函数可以使用可选参数:dtype,它允许我们定义数组元素的预期数据类型:

Instance

用数据类型字符串创建数组:

import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)

Run Instance

对于 iufSU,我们也可以定义大小。

Instance

创建数据类型为 4 字节整数的数组:

import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)

Run Instance

Kada kaiyauwa bai baihun ga kai kaiyauwa, a niyauwa?

Idan gida bai baihun ga kai kaiyauwa, NumPy za kai kaiyauwa ValueError.

ValueError: Ayyukan Python, idan kiyasta a cikin funshon ba a kiyasta ba ko yadda, za a tsara ValueError.

Instance

ValueError: In Python, if the type of the parameter passed to the function is not expected or incorrect, ValueError will be raised.

import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')

Run Instance

Convert the data type of the existing array

The best way to change the data type of an existing array is to use astype() Method copies the array.

astype() The function creates a copy of the array and allows you to specify the data type as a parameter.

Data types can be specified using strings, such as 'f' Means float,'i' Means integer, etc. Or you can also use data types directly, such as float Means float,int Means integer.

Instance

By using 'i' As a parameter value, change data type from float to integer:

import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)

Run Instance

Instance

By using int As a parameter value, change data type from float to integer:

import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)

Run Instance

Instance

Change data type from integer to boolean:

import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

Run Instance