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
- python矩阵中float转int
- Qt中QString转int,float
- float转int
- javascript float转int
- SQLServer int转float
- Qt中int转换成QString float 转QString
- float转int 四舍五入问题
- float转int 四舍五入问题
- 字符串转int/float/double
- c++ char转float,int
- float转int 四舍五入问题
- Oracle中INT、FLOAT、NUMBER区别
- Java 中 float 强制转换为 int
- c++中CString,int,float类型转换
- Oracle中INT、FLOAT、NUMBER区别
- c或c++中int转float中在printf中的问题
- python中float()的实现
- 遇到 float 转 int 的有趣问题
- BZOJ 1968: [Ahoi2005]COMMON 约数研究 思维
- DRML(2016-CVPR)重现过程记录---(8)问题定位_3
- NanUI2创建工程时候需要注意的事项
- HDU 1257
- 【数据结构】中B树的插入,删除,遍历
- python矩阵中float转int
- android超级新手须知
- 正向代理和反向代理
- 安装TensorFlow
- SQL中的内外连接、排序和求平均值的语句
- new与malloc的区别?
- 使用Lombok简化java代码的编写
- fastboot:刷系统中各个img文件
- Java 集合——ConcurrentHashMap