学无先后,达者为师

网站首页 编程语言 正文

python numpy.ndarray中如何将数据转为int型_python

作者:dcjmessi   更新时间: 2022-07-14 编程语言

numpy.ndarray中数据转为int型

首先了解内容与类型

>>>print(a)
(array([[0.01124722],
       [0.21752586],
       [0.05586815],
       [0.03558792]]), array([[ 327],
       [ 366],
       [1887],
       [1153],
       [1792]], dtype=int64))
>>>print(type(a))
<class 'tuple'>
>>>print(a[1])
[[ 327]
 [ 366]
 [1887]
 [1153]
 [1792]]
>>>print(type(a[1]))
<class 'numpy.ndarray'>

接下来可以遍历a[1],对每个元素用list()和tolist()转int,代码如下:

for i in a[1]:
    b = list(i)[0].tolist()

先用list()转为列表类型,[0]表示获取第一个值(其实也只有一个值),此时类型为numpy.int64,然后用tolist()便转为int型。 

numpy.ndarray中数据转为int型

出现错误only size-1 arrays can be converted to Python scalars

在这里插入图片描述

经过分析后发现是数据类型出现的错误。

原数据为 [63],使用type得到数据类型为:<class 'numpy.ndarray'>

故将numpy的ndarray类型转为int (或者你需要的类型,此处为int)

使用 list(m)[0].tolist() 的方法得到如下的结果

63

<class 'int'>

Ok,问题成功解决。

原文链接:https://blog.csdn.net/dcjmessi/article/details/105945792

栏目分类
最近更新