numpy中flatten()函数的使用指南与注意事项
本文详细介绍numpy库中flatten()函数的使用方法。该函数用于将多维数组折叠为一维,支持order参数控制存储顺序。文章通过array、mat对象示例展示其应用,并指出其不适用于普通list,提供了使用列表推导式实现同等效果的替代方案。
flatten函数简介与参数说明
flatten是numpy.ndarray模块下的一个成员函数,其官方文档说明如下:
ndarray.flatten(order='C')
返回一个折叠成一维的数组副本。
参数说明:
|
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. |
flatten函数的使用限制与替代方案
该函数的作用是返回一个被折叠成一维的新数组。需要注意的是,此方法仅适用于numpy的数据类型,即array或mat对象,普通的Python list列表无法直接使用此方法。
flatten函数实际应用示例
具体示例如下:
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'
若希望实现与flatten相同的效果,可以使用列表推导式:
>>> [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])
以上内容为本文的全部介绍,希望能对您的学习有所帮助,也欢迎大家继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













