python矩阵中float转int

问题: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  : gaozhengj@foxmail.com
# @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)

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风醉雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值