前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中flatten( ),matrix.A用法说明

Python中flatten( ),matrix.A用法说明

作者头像
砸漏
发布2020-10-21 15:10:01
8880
发布2020-10-21 15:10:01
举报
文章被收录于专栏:恩蓝脚本

flatten()函数用法

flatten是numpy.ndarray.flatten的一个函数,即返回一个折叠成一维的数组。但是该函数只能适用于numpy对象,即array或者mat,普通的list列表是不行的。

其官方文档是这样描述的

Parameters: ndarray.flatten(order=’C’) Return a copy of the array collapsed into one dimension. 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’.

a是个矩阵或者数组,a.flatten()就是把a降到一维,默认是按横的方向降

那么a.flatten().A又是什么呢? 其实这是因为此时的a是个矩阵,降维后还是个矩阵,矩阵.A(等效于矩阵.getA())变成了数组。具体看下面的例子:

1、用于array对象

代码语言:javascript
复制
    from numpy import *
    a=array([[1,2],[3,4],[5,6]])
    a
array([[1, 2],
  [3, 4],
  [5, 6]])
    a.flatten()
array([1, 2, 3, 4, 5, 6])
    a.flatten('F')
array([1, 3, 5, 2, 4, 6]) # 按列排序
    a.flatten('A')
array([1, 2, 3, 4, 5, 6])

2、用于mat对象

代码语言:javascript
复制
    a=mat([[1,2,3],[4,5,6]])
    a
matrix([[1, 2, 3],
  [4, 5, 6]])
    a.flatten()
matrix([[1, 2, 3, 4, 5, 6]])
    a=mat([[1,2,3],[4,5,6]])
    a
matrix([[1, 2, 3],
  [4, 5, 6]])
    a.flatten()
matrix([[1, 2, 3, 4, 5, 6]])
    y=a.flatten().A 
    shape(y)
(1L, 6L)
    shape(y[0]) 
(6L,)
    a.flatten().A[0] 
array([1, 2, 3, 4, 5, 6])

从中可以看出matrix.A的用法和矩阵发生的变化。

3、但是该方法不能用于list对象,想要list达到同样的效果可以使用列表表达式:

代码语言:javascript
复制
    a=array([[1,2],[3,4],[5,6]])
    [y for x in a for y in x]
[1, 2, 3, 4, 5, 6]

完美实现!!

补充知识:python中矩阵.A是什么意思?

1. 概述

在numpy中矩阵我们十分常用,但有时候我们会将矩阵转化为数组,方法很简单,直接在矩阵名后加 .A 即可。

2. 演示

代码语言:javascript
复制
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/2/21 19:13
# @Author : Arrow and Bullet
# @FileName: .A.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/qq_41800366
from numpy import *

matTest = mat([1, 2])
print(matTest, type(matTest)) # 结果:[[1 2]] <class 'numpy.matrixlib.defmatrix.matrix' 

matTestToArr = matTest.A
print(matTestToArr, type(matTestToArr)) # 结果:[[1 2]] <class 'numpy.ndarray' 

打印结果如下:

# [[1 2]] <class ‘numpy.matrixlib.defmatrix.matrix’ # [[1 2]] <class ‘numpy.ndarray’

希望能够帮助到大家,有什么问题可以 直接评论即可,喜欢有用的话可以点个赞让更多的人看到,如果不够详细的话也可以说,我会及时回复的。

以上这篇Python中flatten( ),matrix.A用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档