Python中的shape和reshape

shape和reshape都是數組array中的方法

  • shape[index] ----- 獲取數組中第index層子數組的元素個數。0代表最外層數組。 例如:
#coding=utf-8
import numpy as np
a = np.array([1,2,3,4,5,6,7,8])  #一維數組(只有一層的數據)
print(a.shape[0])  #值爲8,因爲只有一層數組,裏面有8個元素
print(a.shape[1])  #IndexError: tuple index out of range(沒有第2層數組,下標不存在,元組索引超出範圍)

a = np.array([[1,2,3,4],[5,6,7,8]])  #二維數組(有兩層元素的數組)
print(a.shape[0])  #值爲2,最外層數組中有2個元素,2個元素還是數組。
print(a.shape[1])  #值爲4,內層數組有4個元素。
print(a.shape[2])  #IndexError: tuple index out of range(沒有第3層數組,下標不存在,元組索引超出範圍)

  • reshape((x,y)) ----- 將現有數組的元素,轉成新維度長度的數組。新生成的數組總個數,必須與原數組總數相等,否則就會報錯。
    a = np.array([1,2,3,4,5,6,7,8])  #一維數組
    b=a.reshape((2,4))
    print(b)
    #結果:
    #    [[1 2 3 4]
    #     [5 6 7 8]]

    c=a.reshape((4,2))
    print(c)
    #結果:
    #[[1 2]
    # [3 4]
    # [5 6]
    # [7 8]]

一個參數爲-1時,那麼reshape函數會根據另一個參數的維度計算出數組的另外一個shape屬性值。

    a = np.array([1,2,3,4,5,6,7,8])  #一維數組
    d=a.reshape((-1,4))
    print(d)
    #結果:
    #    [[1 2 3 4]
    #     [5 6 7 8]]

    f=a.reshape((4,-1))
    print(f)
    #結果:
    #[[1 2]
    # [3 4]
    # [5 6]
    # [7 8]]

reshape新生成數組和原數組公用一個內存,不管改變哪個都會互相影響。

    a = np.array([1,2,3,4,5,6,7,8])  #一維數組
    e=a.reshape((2,4))
    e[0][2]=99
    print(e)
    #結果:
    #[[ 1  2 99  4]
    # [ 5  6  7  8]]
    print(a)
    #結果
    #[ 1  2 99  4  5  6  7  8]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章