天天看點

N維數組_1_ndarray介紹1.Numpy中ndarray介紹2.ndarray與Python原生list運算效率對比3.ndarray的屬性4.ndarray形狀5.ndarray類型

import numpy as np
import random
import time
           

1.Numpy中ndarray介紹

score = np.array(
    [[80, 89, 86, 67, 79],
     [78, 97, 89, 67, 81],
     [90, 94, 78, 67, 74],
     [91, 91, 90, 67, 69],
     [76, 87, 75, 67, 86],
     [70, 79, 84, 67, 84],
     [94, 92, 93, 67, 64],
     [86, 85, 83, 67, 80]])
score
           
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
           

2.ndarray與Python原生list運算效率對比

# 使用Python清單可以存儲一維數組,通過清單的嵌套可以實作多元數組,那麼為什麼還需要使用Numpy的ndarray呢?
# 通過運作時間的對比可知為什麼要用ndarray而不是清單嵌套來表示數組

a = []
for i in range(10000):
    a.append(random.random())
# 通過%time魔法方法, 檢視目前行的代碼運作一次所花費的時間
%time sum1 = sum(a)
b = np.array(a)
%time sum1 = sum(b)
           
Wall time: 999 µs
Wall time: 5.98 ms
           

3.ndarray的屬性

score
           
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
           
# 數組次元的元組
score.shape  
           
(8, 5)
           
#數組維數
score.ndim
           
2
           
#數組中元素數量
score.size
           
40
           
# 一個數組元素的長度(位元組)
score.itemsize
           
4
           
# 數組元素的類型
score.dtype
           
dtype('int32')
           

4.ndarray形狀

# 一維數組
b = np.array([1, 2, 3, 4])
b.shape
           
(4,)
           
# 二維數組
a = np.array([[1, 2, 3], [4, 5, 6]])
a.shape
           
(2, 3)
           
# 三位數組  對于三維數組的了解:可以将其想象成描述三維空間中的點,将(2,2,3)了解為立方體的長為2,寬為2,高為3
c = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
c.shape
           

5.ndarray類型

score.dtype
           
dtype('int32')
           
numpy.dtype
           
# 指定資料類型建立數組,注意:若不指定,整數預設int64,小數預設float64
a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
a.dtype
           
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)
           

繼續閱讀