numpy.ndarray中数据转为int型
首先了解内容与类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
>>> 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,代码如下:
1
2
|
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