python矩阵中float转int

来源:互联网 发布:申请域名后怎么使用 编辑:程序博客网 时间:2024/06/14 10:21

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


修改时间:2017年5月24日

>>>import numpy as np>>>sample = np.mat([[1.0, 2.0], [3.0, 4.0]])>>>samplematrix([[ 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  : gaozhengj@foxmail.com# @Software : PyCharmimport numpy as npsample = 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)

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

1 0
原创粉丝点击