更改Python中给定NumPy数组的数据类型
我们有一个名为**astype(data_type)**的方法来更改NumPy数组的数据类型。如果我们有一个类型为**float64**的NumPy数组,那么我们可以通过将数据类型提供给NumPy数组的**astype()**方法将其更改为**int32**。
我们可以使用**dtype**类检查NumPy数组的类型。让我们检查示例NumPy数组的数据类型。
示例
# importing numpy library import numpy as np # creating numpy array array = np.array([1, 2, 3, 4, 5]) # printing the data type of the numpy array print(array.dtype)
输出
如果运行上述代码,您将获得以下结果。
int32
让我们看看如何将NumPy数组的数据类型从**float64**更改为**int32**。
示例
# importing numpy library
import numpy as np
# creating numpy array of type float64
array = np.array([1.5, 2.6, 3.7, 4.8, 5.9])
# type of array before changing
print(f'Before changing {array.dtype}')
# changing the data type of numpy array using astype() method
array = array.astype(np.int32)
# type of array after changing
print(f'\nAfter changing {array.dtype}')输出
如果运行上述程序,您将获得以下结果。
Before changing float64 After changing int32
我们可以使用NumPy模块中存在的任何数据类型或Python的一般数据类型。您可以在此处找到NumPy中存在的数据类型列表。
结论
我希望您已经学习了NumPy数组的数据类型转换。如果您在教程中遇到任何问题,请在评论部分提及。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP