python矩阵中float转int

您所在的位置:网站首页 float型转int python矩阵中float转int

python矩阵中float转int

2023-03-24 22:20| 来源: 网络整理| 查看: 265

问题:numpy定义的矩阵A中所有元素为float类型,现要求将A中所有元素转化为int类型。

修改时间:2017年5月24日

>>>import numpy as np >>>sample = np.mat([[1.0, 2.0], [3.0, 4.0]]) >>>sample matrix([[ 1., 2.], [ 3., 4.]]) >>>sample.astype(np.int) matrix([[1, 2], [3, 4]])

SciPy.org对数据类型的介绍 https://docs.scipy.org/doc/numpy/user/basics.types.html

以下是以前2017/5/12的老版本

本人愚钝,不想使用for循环遍历矩阵,挨个进行类型转换,故想用map对矩阵中的元素进行类型转换,但是实际过程中一直提示如下错误:

{TypeError}only length-1 arrays can be converted to Python scalars

必须先转换成list类型,才能使用map进行类型转换。具体代码如下,为了便于理解,每一步后面都配有相应的注释,标明了变量的类型和值。

#!/usr/bin/env python3.x # -*- coding: utf-8 -*- # @Time : 2017/5/12 15:47 # @Author : GaoZhengjie # @Contact : [email protected] # @Software : PyCharm import numpy as np sample = np.mat([[1.0, 2.0], [3.0, 4.0]]) # sample = {matrix}[[1.0 2.0]\n[3.0 4.0]] sample = list(map(int, sample)) # 首先将sample以行为主序进行扁平化 step_1 = sample.flatten() # step_1 = {matrix}[[1.0 2.0 3.0 4.0]] step_2 = step_1.tolist() # step_2 = {list}[[1.0, 2.0, 3.0, 4.0]] step_3 = step_2[0] # step_3 = {list}[1.0, 2.0, 3.0, 4.0] # 从python3.x开始map必须搭配list才能使用 step_4 = list(map(int, step_3)) # step_4 = {list}[1, 2, 3, 4] step_5 = np.mat(step_4).reshape(sample.shape) # step_5 = {matrix}[[1 2]\n[3 4]] # 将上述五个步骤揉在一起,如下: # sample = np.mat(list(map(int, sample.flatten().tolist()[0]))).reshape(sample.shape) print(sample)

从代码长度就不难看出,这个方法还是太麻烦了些。还请大家不吝赐教,万分感谢。

附 该文章于2017年5月12日于CSDN上首次发表,2017年12月22日搬家至此!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3