Reshape,flatten,ravel data in NumPy is flattened, multidimensional arrays become one-dimensional arrays

Source: Internet
Author: User

Reshape,flatten,ravel data in NumPy is flattened, multidimensional arrays become one-dimensional arrays
import numpy as np
Using the Array object
arr1=np.arange(12).reshape(3,4)print(arr1)print(type(arr1))
[[ 0  1  2  3] [ 4  5  6  7] [ 8  9 10 11]]<class ‘numpy.ndarray‘>
    • Flatten Flatten
a=arr1.flatten() # 默认参数order=C,按照行进行展平;order=F,按照列进行展平,交叉展平;#A 或K参数用的不多,顾不变多记,到时候找到会用即可a[2]=1000print(arr1)  # arr1 并没有改变,flatten 返回的是copya
[[ 0  1  2  3] [ 4  5  6  7] [ 8  9 10 11]]array([   0,    1, 1000,    3,    4,    5,    6,    7,    8,    9,   10,         11])
    • Reshape Transform
arr1=np.arange(12).reshape(3,4)b=arr1.reshape(-1)  #  b=arr1.reshape((-1)) 等同的效果意义 ,  b[2]=1000print(arr1)# 返回的是视图view
[[   0    1 1000    3] [   4    5    6    7] [   8    9   10   11]]
    • Ravel transform
arr1=np.arange(12).reshape(3,4)c=arr1.ravel()c
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
c[2]=10001arr1  # 返回的是视图view
array([[    0,     1, 10001,     3],       [    4,     5,     6,     7],       [    8,     9,    10,    11]])
    • Resize
arr1=np.arange(12).reshape(3,4)arr1.resize((4,3))  #  无返回值,即会对原始多维数组直接进行修改,也就是不能赋值arr1
array([[ 0,  1,  2],       [ 3,  4,  5],       [ 6,  7,  8],       [ 9, 10, 11]])
Working with a matrix object
# 使用matrix对象的时候,返回的仍是matrix,得不到想要的结果,不过该matrix仍然可以使用numpy中的一些方法对其操作,比如sum,min,max等等d=np.matrix(np.arange(12).reshape(3,4))d
matrix([[ 0,  1,  2,  3],        [ 4,  5,  6,  7],        [ 8,  9, 10, 11]])
matrix([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])

Reshape,flatten,ravel data in NumPy is flattened, multidimensional arrays become one-dimensional arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.