经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » NumPy » 查看文章
numpy下的flatten()函数用法详解
来源:jb51  时间:2019/5/28 8:56:14  对本文有异议

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对象

  1. from numpy import *
  2. >>>a=array([[1,2],[3,4],[5,6]]) ###此时a是一个array对象
  3. >>>a
  4. array([[1,2],[3,4],[5,6]])
  5. >>>a.flatten()
  6. array([1,2,3,4,5,6])

2、用于mat对象

  1. >>> a=mat([[1,2,3],[4,5,6]])
  2. >>> a
  3. matrix([[1, 2, 3],
  4. [4, 5, 6]])<br>>>> a.flatten()<br>matrix([[1, 2, 3, 4, 5, 6]])<br>

3、但是该方法不能用于list对象

  1. >>> a=[[1,2,3],[4,5,6],['a','b']]
  2. [[1, 2, 3], [4, 5, 6], ['a', 'b']]
  3. >>> a.flatten() ###报错
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. AttributeError: 'list' object has no attribute 'flatten'

想要list达到同样的效果可以使用列表表达式:

  1. >>> [y for x in a for y in x]
  2. [1, 2, 3, 4, 5, 6, 'a', 'b']

4、用在矩阵

  1. >>> a = [[1,3],[2,4],[3,5]]
  2. >>> a = mat(a)
  3. >>> y = a.flatten()
  4. >>> y
  5. matrix([[1, 3, 2, 4, 3, 5]])
  6. >>> y = a.flatten().A
  7. >>> y
  8. array([[1, 3, 2, 4, 3, 5]])
  9. >>> shape(y)
  10. (1, 6)
  11. >>> shape(y[0])
  12. (6,)
  13. >>> y = a.flatten().A[0]
  14. >>> y
  15. array([1, 3, 2, 4, 3, 5])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号