改变给定的numpy数组的数据类型

改变给定的numpy数组的数据类型

在这篇文章中,我们将看到改变给定的numpy数组的dtype的方法。为了改变给定数组对象的dtype,我们将使用numpy.astype()函数。该函数需要一个参数,即目标数据类型。该函数支持所有的通用类型和内置数据类型。

问题#1 :给定一个numpy数组,其基础数据为’int32’类型。将给定对象的dtype改为’float64’。

解决方案:我们将使用numpy.astype()函数来改变给定的numpy数组的底层数据的数据类型。

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
  
# Print the array
print(arr)

输出 :

改变给定的numpy数组的数据类型

现在我们将检查给定数组对象的dtype。

# Print the dtype
print(arr.dtype)

输出 :

改变给定的numpy数组的数据类型

正如我们在输出中看到的,给定数组对象的当前dtype是’int32’。现在我们要把它改为’float64’类型。

# change the dtype to 'float64'
arr = arr.astype('float64')
  
# Print the array after changing
# the data type
print(arr)
  
# Also print the data type
print(arr.dtype)

输出 :

改变给定的numpy数组的数据类型

改变给定的numpy数组的数据类型

问题#2 :给定一个numpy数组,其基础数据是’int32’类型。将给定对象的dtype改为’complex128’。

解决方案:我们将使用numpy.astype()函数来改变给定的numpy数组的底层数据的数据类型。

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
  
# Print the array
print(arr)

输出 :

改变给定的numpy数组的数据类型

现在我们将检查给定数组对象的dtype。

# Print the dtype
print(arr.dtype)

输出 :

改变给定的numpy数组的数据类型

正如我们在输出中看到的,给定数组对象的当前dtype是’int32’。现在我们将把它改为’complex128’类型。

# change the dtype to 'complex128'
arr = arr = arr.astype('complex128')
  
# Print the array after changing
# the data type
print(arr)
# Also print the data type
print(arr.dtype)

输出 :

改变给定的numpy数组的数据类型

改变给定的numpy数组的数据类型

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程