numpy中flatten()函数如何使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
flatten是numpy.ndarray.flatten的一个函数,其官方文档是这样描述的:
ndarray.flatten(order='C')
Return a copy of the array collapsed into one dimension.
Parameters:
order : {‘C', ‘F', ‘A', ‘K'}, optional ‘C' means to flatten in row-major (C-style) order. ‘F' means to flatten in column-major (Fortran- style) order. ‘A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K' means to flatten a in the order the elements occur in memory. The default is ‘C'. | |
Returns: | y : ndarray A copy of the input array, flattened to one dimension. |
即返回一个折叠成一维的数组。但是该函数只能适用于numpy对象,即array或者mat,普通的list列表是不行的。
例子:
1、用于array对象
from numpy import *
>>>a=array([[1,2],[3,4],[5,6]]) ###此时a是一个array对象
>>>a
array([[1,2],[3,4],[5,6]])
>>>a.flatten()
array([1,2,3,4,5,6])
2、用于mat对象
>>> a=mat([[1,2,3],[4,5,6]])
>>> a
matrix([[1, 2, 3],
[4, 5, 6]])<br>>>> a.flatten()<br>matrix([[1, 2, 3, 4, 5, 6]])<br>
3、但是该方法不能用于list对象
>>> a=[[1,2,3],[4,5,6],['a','b']]
[[1, 2, 3], [4, 5, 6], ['a', 'b']]
>>> a.flatten() ###报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'flatten'
想要list达到同样的效果可以使用列表表达式:
>>> [y for x in a for y in x]
[1, 2, 3, 4, 5, 6, 'a', 'b']
4、用在矩阵
>>> a = [[1,3],[2,4],[3,5]]
>>> a = mat(a)
>>> y = a.flatten()
>>> y
matrix([[1, 3, 2, 4, 3, 5]])
>>> y = a.flatten().A
>>> y
array([[1, 3, 2, 4, 3, 5]])
>>> shape(y)
(1, 6)
>>> shape(y[0])
(6,)
>>> y = a.flatten().A[0]
>>> y
array([1, 3, 2, 4, 3, 5])
看完上述内容,你们掌握numpy中flatten()函数如何使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。