网络编程
位置:首页>> 网络编程>> Python编程>> python numpy.ndarray中如何将数据转为int型

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

作者:dcjmessi  发布时间:2022-11-21 16:14:09 

标签:python,numpy.ndarray,数据,int

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

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

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

原数据为 [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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com