在Python中更改给定的numpy数组的数据类型

Change data type of given numpy array in Python

我们可以使用dtype类检查numpy数组的类型。让我们检查示例numpy数组的数据类型。

<!-

现场演示

->

1
2
3
4
5
6
# 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)

输出量

如果运行上面的代码,您将得到以下结果。

1
int32

让我们看看如何将numpy数组的数据类型从float64更改为&int32。

<!-

现场演示

->

1
2
3
4
5
6
7
8
9
10
11
# 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'
After changing {array.dtype}')

输出量

如果运行上述程序,则将得到以下结果。

1
2
Before changing float64
After changing int32

我们可以使用numpy模块中存在的任何数据类型或Python的常规数据类型。您可以在此处找到numpy中存在的数据类型列表。

结论

希望您了解了numpy数组的数据类型转换。如果您遇到与本教程相关的任何问题,请在评论部分中提及它们。