numpy下的flatten()函数用法详解

yipeiwu_com5年前Python基础

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])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解Python中where()函数的用法

where()的用法 首先强调一下,where()函数对于不同的输入,返回的只是不同的。 1当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组 2当数组是二维数组时,满足条件...

Python3.x版本中新的字符串格式化方法

我们知道Python3.x引入了新的字符串格式化语法。不同于Python2.x的 复制代码 代码如下: "%s %s "%(a,b)  Python3.x是 复制代码 代码...

对Python3中的input函数详解

对Python3中的input函数详解

下面介绍python3中的input函数及其在python2及pyhton3中的不同。 python3中的ininput函数,首先利用help(input)函数查看函数信息: 以上信息...

详细解读tornado协程(coroutine)原理

详细解读tornado协程(coroutine)原理

tornado中的协程是如何工作的 协程定义 Coroutines are computer program components that generalize subroutin...

python3+requests接口自动化session操作方法

在进行接口自动化测试时,有好多接口都基于登陆接口的响应值来关联进行操作的,在次之前试了很多方法,都没有成功,其实很简单用session来做。 1、在登陆接口创建一个全局session...