python中dtype
时间: 2024-01-08 16:21:34 浏览: 26
在Python中,dtype是NumPy库中的一个对象,用于描述数组中元素的数据类型。它可以用于创建数组、指定数组的数据类型以及执行数据类型转换等操作。
以下是一些关于dtype的介绍和示例:
1. 创建数组时指定数据类型:
```python
import numpy as np
arr = np.array([1, 2, 3], dtype=np.float64)
print(arr.dtype) # 输出:float64
```
2. 查看数组的数据类型:
```python
import numpy as np
arr = np.array([1, 2, 3])
print(arr.dtype) # 输出:int64
```
3. 数据类型转换:
```python
import numpy as np
arr = np.array([1,2, 3])
arr_float = arr.astype(np.float64)
print(arr_float.dtype) # 输出:float64
```
4. 使用dtype对象创建数组:
```python
import numpy as np
dt = np.dtype(int)
arr = np.array([1, 2, 3], dtype=dt)
print(arr.dtype) # 输出:int32
```
5. 使用dtype对象指定数组元素的数据类型:
```python
import numpy as np
dt = np.dtype([('name', np.str_, 16), ('age', np.int32)])
arr = np.array([('Alice', 25), ('Bob', 30)], dtype=dt)
print(arr.dtype) # 输出:[('name', '<U16'), ('age', '<i4')]
```