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代码太长换行的实现

末尾加 \ 或 Enter ,回车使用看情况,\通用。 如果是print字符串换行,可以加三个单引号或三个双引号,但是这样回车换行会保留,若要呈现无换行的字符串,引号中每行末尾可加 \...

django框架model orM使用字典作为参数,保存数据的方法分析

本文实例讲述了django框架model orM使用字典作为参数,保存数据的方法。分享给大家供大家参考,具体如下: 假设有一个字典,里面已经有了所有相关信息,现在想利用这个字典作为参数,...

Python httplib模块使用实例

httplib模块是一个底层基础模块,实现的功能比较少,正常情况下比较少用到.推荐用urllib, urllib2, httplib2. HTTPConnection 对象 class...

python通过字典dict判断指定键值是否存在的方法

本文实例讲述了python通过字典dict判断指定键值是否存在的方法。分享给大家供大家参考。具体如下: python中有两种方法可以判断指定的键值是否存在,一种是通过字典对象的方法 ha...

python使用Plotly绘图工具绘制散点图、线形图

python使用Plotly绘图工具绘制散点图、线形图

今天在研究Plotly绘制散点图的方法,供大家参考,具体内容如下 使用Python3.6 + Plotly Plotly版本2.0.0 在开始之前先说说,还需要安装库Numpy,安装方法...