当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python Numpy matrix.astype()用法及代码示例

借助Numpy matrix.astype()方法,我们能够转换矩阵的类型,但是问题是数据丢失,如果我们想将float转换为int,那么某些数据将丢失。此方法有助于矩阵的类型转换。

用法: matrix.astype()

返回: 类型转换后返回矩阵。


范例1:
在此示例中,我们可以看到如何使用以下方法将浮点型矩阵转换为int型矩阵matrix.astype()方法。

# import the important module in python 
import numpy as np 
            
# make a matrix with numpy 
gfg = np.matrix('[1.2, 2.8, 3.1, 4.5]') 
            
# applying matrix.astype() method 
geeks = gfg.astype(int) 
      
print(geeks)
输出:
[[1 2 3 4]]

范例2:

# import the important module in python 
import numpy as np 
            
# make a matrix with numpy 
gfg = np.matrix('[1.1, 2, 3.5; 4.2, 5.5, 6; 7, 8, 9.3]') 
            
# applying matrix.astype() method 
geeks = gfg.astype(int) 
      
print(geeks)
输出:
[[1 2 3]
 [4 5 6]
 [7 8 9]]


相关用法


注:本文由纯净天空筛选整理自Jitender_1998大神的英文原创作品 Python | Numpy matrix.astype()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。