[NumPy 學習筆記] - No.1 使用NumPy創建數組

numpy是python中非常有用的一個庫,我們可以使用numpy創建大型的高維數組並進行運算。這裏記錄一下numpy一些常用的方法。如果想仔細研究numpy的強大功能還需要翻閱NumPy API文檔

創建數組

import numpy as np
創建標量

我們使用numpy來創建一個簡單的數字

# 創建一個float類型的數字
x = np.array(6.0) # 稍後會解釋什麼叫np.array()
print ("x: ", x)
# Number of dimensions
print ("x ndim: ", x.ndim)
# Dimensions
print ("x shape:", x.shape)
# Size of elements
print ("x size: ", x.size)
# Data type
print ("x dtype: ", x.dtype)

print(x)

結果如下所示:

x: 6.0
x ndim: 0
x shape: ()
x size: 1
x dtype: float64

ndim和shape,size,究竟是什麼呢?我們再多看兩個例子

創建一維數組和多維數組
# 1-D Array
x = np.array([1 , 2 , 1.7])
print ("x: ", x)
print ("x ndim: ", x.ndim)
print ("x shape:", x.shape)
print ("x size: ", x.size)
print ("x dtype: ", x.dtype) # notice the float datatype

結果如下:

x: [ 1. 2. 1.7]
x ndim: 1
x shape: (3,)
x size: 3
x dtype: float64

再來看三維數組

# 3-D array (matrix)
x = np.array([[[1,2,3], [4,5,6], [7,8,9]]])
print ("x:\n", x)
print ("x ndim: ", x.ndim)
print ("x shape:", x.shape)
print ("x size: ", x.size)
print ("x dtype: ", x.dtype)

結果如下:

x:
[[[1 2 3]
[4 5 6]
[7 8 9]]]
x ndim: 3
x shape: (1, 3, 3)
x size: 9
x dtype: int32

在numpy中,我們使用ndarray這種數據類型來存儲數組,使用np.array()來創建ndarray;ndarray由數組數據和描述數據的元數據組成。

在這裏插入圖片描述

ndim: 變量x的維度,如果是數字就是0,如果是1維數組就是1,二維數組就是2,以此類推。

shape:變量x的形狀,如果是數字就是(),如果是1維數組就是形如(3,),如果是二維數組就形如(3,4),以此類推 。

size: 變量x所有元素的總數;例如一個3x4的二維數組就是12個元素。

dtype:變量中元素的類型,numpy中有着豐富的數據類型。

其他方法

numpy數組和list可以互相轉換:

a = [1,2,3]
# list 轉 numpy
x = np.array(a)
# ndarray 轉 list
b = x.tolist()

在numpy中還有一些創建數組的方法,例如:

我們可以使用np.arange()創建一個連續的等差數組:

# np.arange([start, ]stop, [step, ]dtype=None)

import numpy as np
nd1 = np.arange(6)#array([0 1 2 3 4 5])
nd2 = np.arange(2,6)#array([2 3 4 5])
nd3 = np.arange(2,10,2) #array([2 4 6 8])

我們通常使用np.arange() 配合reshape()來生成數組

nd4 = np.arange(6).reshape(2,-1)
print(nd4)

nd4:
[[0 1 2]
[3 4 5]]

使用numpy來創建零矩陣,單位矩陣等:

# 特殊矩陣
print ("np.zeros((2,2)):\n", np.zeros((2,2))) #零矩陣
print ("np.ones((2,2)):\n", np.ones((2,2))) #全部是1的矩陣
print ("np.eye((2)):\n", np.eye((2))) #單位矩陣
print ("np.random.random((2,2)):\n", np.random.random((2,2))) #隨機矩陣

np.zeros((2,2)):
[[ 0. 0.]
[ 0. 0.]]
np.ones((2,2)):
[[ 1. 1.]
[ 1. 1.]]
np.eye((2)):
[[ 1. 0.]
[ 0. 1.]]
np.random.random((2,2)):
[[ 0.77997581 0.27259261]
[ 0.27646426 0.80187218]]

資料參考:practicalAI

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章