1. 程式人生 > >Numpy學習一:array數組對象

Numpy學習一:array數組對象

通過 ros 不變 3.1 nbsp ebo 所有 not 組合鍵

NumPy是Python的一個高性能科學計算和數據分析基礎庫,提供了功能強大的多維數組對象ndarray
jupyter notebook快速執行代碼的快捷鍵:鼠標點擊選中要指定的代碼框,Shift + Enter組合鍵直接執行代碼框中的全部代碼。 Alt + Enter組合鍵執行完代碼框中的代碼在代碼框的下面再添加一個空代碼框。

1、創建數組

#引入numpy,並重命名為np,方便使用
import numpy as np

1.1、使用numpy內置的array函數創建數組

#創建一維數組
arr1 = np.array([1,2,3])
print(arr1)

結果:[1 2 3]

#創建二維數組
arr2 = np.array([[1,2,3],[4,5,6]])
print(arr2)

結果:[[1 2 3] [4 5 6]]

1.2、使用arange函數創建數組

#使用arange函數創建包含0到9 十個數字的一維數組

#註意:arange函數返回的數組默認第一個元素是0,結束元素是指定的數值前一個數字9
arr_1 = np.arange(10)
print(arr_1)

結果:[0 1 2 3 4 5 6 7 8 9]

#通過arange函數設置“開始、結束、步長”三個參數創建包含1到10所有奇數的一維數組

#從1開始,到10前一位結束,步長為2表示相鄰兩個元素的差值是2
print(arr_2)


arr_2 = np.arange(1,10,2)

結果:[1 3 5 7 9]

1.3、全0、全1數組

#使用zeros函數創建一個包含10個全0數字的一維數組
z1 = np.zeros(10)
print(z1)

結果:[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

#創建3行4列的二維全0數組
z2 = np.zeros((3,4))
print(z2)

結果:[[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]]

#創建全1數組
o1 = np.ones(5)
print(o1)

結果:[ 1. 1. 1. 1. 1.]

#創建3行4列全1二維數組
o2 = np.ones((3,4))
print(o2)

結果:[[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 1.]]

2、數組的屬性方法

#查看數組o2各維度的大小
o2.shape
#運行結果是一個元組(3,4)表示第1維的大小是3(也是就是3行),第2維的大小是4(也就是4列)

結果:(3, 4)

#查看o2第1維的大小(行數)
o2.shape[0]

結果:3

#查看o2第2維的大小(列數)
o2.shape[1]

結果:4

#查看數組中元素類型
o2.dtype

結果:dtype(‘float64‘)

#類型轉換函數astype,數組元素由float64類型轉換成int32類型,並返回一個新的數組o2_1,原數組o2元素類型不變
o2_1 = o2.astype(np.int32)

#o2數組類型不變
o2.dtype

結果:dtype(‘float64‘)

#o2_1數組中元素類型為int32
o2_1.dtype

結果:dtype(‘int32‘)

#創建字符串類型數組
arr_string = np.array(["12.78","23.15","34.5"])
arr_string.dtype

結果:dtype(‘<U5‘)#dtype(‘<U5‘)表示字符串不超過5位

#將字符串數組轉換成浮點類型數組
arr_float = arr_string.astype(np.float64)
print(arr_float)

結果:[ 12.78 23.15 34.5 ]

#float類型數組轉換成整型數組,小數部分將會被截斷
arr_int = arr_float.astype(np.int32)
print(arr_int)

結果:[12 23 34]

#numpy自動識別元素類型
np.array([1,2,3]).dtype

結果:dtype(‘int32‘)

Numpy學習一:array數組對象