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

作者:波比12 时间:2021-08-19 04:27:54 

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

来源:https://www.cnblogs.com/itdyb/p/5796834.html

标签:numpy,flatten
0
投稿

猜你喜欢

  • Python模拟百度登录实例详解

    2023-07-18 19:06:46
  • python操作yaml说明

    2022-03-05 14:47:43
  • Python安装selenium包详细过程

    2023-04-12 00:05:31
  • SQL语句实例说明 方便学习mysql的朋友

    2012-11-30 20:02:43
  • Jenkins配置maven项目之打包、部署、发布的全过程

    2023-08-07 19:14:29
  • python手机号前7位归属地爬虫代码实例

    2021-01-23 05:20:34
  • Pandas之Fillna填充缺失数据的方法

    2022-11-17 20:17:12
  • python k-近邻算法实例分享

    2022-03-26 14:47:17
  • 详解使用python爬取抖音app视频(appium可以操控手机)

    2023-09-20 13:30:32
  • Python Numpy中数组的集合操作详解

    2023-12-04 12:02:24
  • Pandas直接读取sql脚本的方法

    2022-08-16 20:16:34
  • 详解Python程序与服务器连接的WSGI接口

    2021-11-19 03:57:10
  • Python基于yaml文件配置logging日志过程解析

    2022-04-02 10:50:36
  • django rest framework 实现用户登录认证详解

    2023-05-10 10:19:05
  • 微信公众号可通过现金红包接口发放微信支付现金红包(附开发教程)

    2023-06-28 10:24:42
  • 轻松掌握 MySQL的数字类型以及建库策略

    2008-11-27 16:09:00
  • python结合多线程爬取英雄联盟皮肤(原理分析)

    2023-05-31 21:49:37
  • python 类相关概念理解

    2023-02-17 21:16:47
  • PHP利用func_get_args和func_num_args函数实现函数重载实例

    2023-06-15 09:25:51
  • SQL Server中多行多列连接成为单行单列

    2008-12-09 14:39:00
  • asp之家 网络编程 m.aspxhome.com