網(wǎng)站首頁 編程語言 正文
Numpy中的N維數(shù)組(ndarray)
Numpy 中的數(shù)組是一個元素表(通常是數(shù)字),所有元素類型相同,由正整數(shù)元組索引。在 Numpy 中,數(shù)組的維數(shù)稱為數(shù)組的秩。給出數(shù)組沿每個維的大小的整數(shù)元組稱為數(shù)組的形狀。Numpy 中的數(shù)組類稱為ndarray。Numpy 數(shù)組中的元素可以使用方括號訪問,并且可以使用嵌套的 Python 列表進行初始化。
例子 :
[[ 1, 2, 3],
[ 4, 2, 5]]
Here, rank = 2 (as it is 2-dimensional or it has 2 axes)
First dimension(axis) length = 2, second dimension has length = 3
overall shape can be expressed as: (2, 3)
# 演示基本數(shù)組特征的 Python 程序
import numpy as np
# 創(chuàng)建數(shù)組對象
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
# arr 對象的打印類型
print("Array is of type: ", type(arr))
# 打印數(shù)組維度(軸)
print("No. of dimensions: ", arr.ndim)
# 陣列的打印形狀
print("Shape of array: ", arr.shape)
# 數(shù)組的打印大小(元素總數(shù))
print("Size of array: ", arr.size)
# 打印數(shù)組中元素的類型
print("Array stores elements of type: ", arr.dtype)
輸出 :
Array is of type: ?<class 'numpy.ndarray'>
No. of dimensions: ?2
Shape of array: ?(2, 3)
Size of array: ?6
Array stores elements of type: ?int64
數(shù)組創(chuàng)建
在 NumPy 中有多種創(chuàng)建數(shù)組的方法。
- 例如,您可以使用array函數(shù)從常規(guī) Python列表或元組創(chuàng)建一個數(shù)組。 結(jié)果數(shù)組的類型是從序列中元素的類型推導(dǎo)出來的。****
- 通常,數(shù)組的元素最初是未知的,但它的大小是已知的。因此,NumPy 提供了幾個函數(shù)來創(chuàng)建具有初始占位符內(nèi)容的數(shù)組。這些最大限度地減少了增長陣列的必要性,這是一項昂貴的操作。
例如: ?np.zeros、np.ones、np.full、np.empty 等。 - 為了創(chuàng)建數(shù)字序列,NumPy 提供了一個類似于 range 的函數(shù),它返回數(shù)組而不是列表。
- arange: 返回給定間隔內(nèi)均勻分布的值。步長是指定的。
- linspace: 返回給定間隔內(nèi)均勻分布的值。編號_?的元素被返回。
-
重塑數(shù)組: 我們可以使用reshape方法來重塑數(shù)組。考慮一個形狀為 (a1, a2, a3, ..., aN) 的數(shù)組。我們可以重新整形并將其轉(zhuǎn)換為另一個形狀為 (b1, b2, b3, ..., bM) 的數(shù)組。唯一需要的條件是:
a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM 。(即數(shù)組的原始大小保持不變。) - 扁平化數(shù)組: 我們可以使用扁平化方法將數(shù)組的副本折疊成一維。它接受order參數(shù)。默認(rèn)值為“C”(用于行優(yōu)先順序)。使用“F”表示列主要順序。
注意: 數(shù)組的類型可以在創(chuàng)建數(shù)組時顯式定義。
# 演示數(shù)組創(chuàng)建技術(shù)的 Python 程序
import numpy as np
# 從浮點類型的列表創(chuàng)建數(shù)組
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)
# 從元組創(chuàng)建數(shù)組
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
# 創(chuàng)建一個全為零的 3X4 數(shù)組
c = np.zeros((3, 4))
print ("\nAn array initialized with all zeros:\n", c)
# 創(chuàng)建一個復(fù)雜類型的常量值數(shù)組
d = np.full((3, 3), 6, dtype = 'complex')
print ("\nAn array initialized with all 6s."
"Array type is complex:\n", d)
輸出 :
Array created using passed list:
?[[ 1. ?2. ?4.]
?[ 5. ?8. ?7.]]
Array created using passed tuple:
?[1 3 2]
An array initialized with all zeros:
?[[ 0. ?0. ?0. ?0.]
?[ 0. ?0. ?0. ?0.]
?[ 0. ?0. ?0. ?0.]]
An array initialized with all 6s. Array type is complex:
?[[ 6.+0.j ?6.+0.j ?6.+0.j]
?[ 6.+0.j ?6.+0.j ?6.+0.j]
?[ 6.+0.j ?6.+0.j ?6.+0.j]]
數(shù)組索引
了解數(shù)組索引的基礎(chǔ)知識對于分析和操作數(shù)組對象很重要。NumPy 提供了許多方法來進行數(shù)組索引。
- 切片: 就像 python 中的列表一樣,NumPy 數(shù)組可以切片。由于數(shù)組可以是多維的,因此您需要為數(shù)組的每個維度指定一個切片。
- 整數(shù)數(shù)組索引: 在此方法中,傳遞列表以對每個維度進行索引。完成對應(yīng)元素的一對一映射以構(gòu)造一個新的任意數(shù)組。
- 布爾數(shù)組索引: 當(dāng)我們想從數(shù)組中選擇滿足某些條件的元素時使用此方法。
# 在 numpy 中演示索引的 Python 程序
import numpy as np
# 一個示例數(shù)組
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# 切片數(shù)組
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
# 整數(shù)數(shù)組索引示例
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),"
"(3, 0):\n", temp)
# 布爾數(shù)組索引示例
cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)
輸出 :
Array with first 2 rows and alternatecolumns(0 and 2):
?[[-1. ?0.]
?[ 4. ?6.]]
Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):
?[ 4. ?6. ?0. ?3.]
Elements greater than 0:
?[ 2. ? 4. ? 4. ? 6. ? 2.6 ?7. ? 8. ? 3. ? 4. ? 2. ]
基本操作
NumPy 提供了大量的內(nèi)置算術(shù)函數(shù)。
對單個數(shù)組的操作: 我們可以使用重載的算術(shù)運算符對數(shù)組進行元素操作以創(chuàng)建一個新數(shù)組。在 +=、-=、*= 運算符的情況下,將修改現(xiàn)有數(shù)組。
# 演示單個數(shù)組的基本操作的 Python 程序
import numpy as np
a = np.array([1, 2, 5, 3])
# 每個元素加 1
print ("Adding 1 to every element:", a+1)
# 從每個元素中減去 3
print ("Subtracting 3 from each element:", a-3)
# 將每個元素乘以 10
print ("Multiplying each element by 10:", a*10)
# 平方每個元素
print ("Squaring each element:", a**2)
# 修改現(xiàn)有數(shù)組
a *= 2
print ("Doubled each element of original array:", a)
# 數(shù)組轉(zhuǎn)置
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
輸出 :
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1 ?2 ?0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 ?4 25 ?9]
Doubled each element of original array: [ 2 ?4 10 ?6]
Original array:
?[[1 2 3]
?[3 4 5]
?[9 6 0]]
Transpose of array:
?[[1 3 9]
?[2 4 6]
?[3 5 0]]
一元運算符:許多一元運算作為 ndarray類的方法提供。這包括 sum、min、max 等。這些函數(shù)也可以通過設(shè)置軸參數(shù)來逐行或逐列應(yīng)用。
# 在 numpy 中演示一元運算符的 Python 程序
import numpy as np
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# 數(shù)組的最大元素
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# 數(shù)組的最小元素
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# 數(shù)組元素之和
print ("Sum of all array elements:",
arr.sum())
# 每行的累積總和
print ("Cumulative sum along each row:\n",
arr.cumsum(axis = 1))
輸出 :
Largest element is: 9
Row-wise maximum elements: [6 7 9]
Column-wise minimum elements: [1 1 2]
Sum of all array elements: 38
Cumulative sum along each row:
[[ 1 ?6 12]
?[ 4 11 13]
?[ 3 ?4 13]]
二元運算符: 這些操作適用于數(shù)組元素并創(chuàng)建一個新數(shù)組。您可以使用所有基本的算術(shù)運算符,如 +、-、/、等。如果是 +=、-=、 ?= 運算符,則會修改現(xiàn)有數(shù)組。
# 在 Numpy 中演示二元運算符的 Python 程序
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# 添加數(shù)組
print ("Array sum:\n", a + b)
# 乘法數(shù)組(元素乘法)
print ("Array multiplication:\n", a*b)
# 矩陣乘法
print ("Matrix multiplication:\n", a.dot(b))
輸出:
Array sum:
[[5 5]
?[5 5]]
Array multiplication:
[[4 6]
?[6 4]]
Matrix multiplication:
[[ 8 ?5]
?[20 13]]
通用函數(shù) (ufunc): ?NumPy 提供熟悉的數(shù)學(xué)函數(shù),例如 sin、cos、exp 等。這些函數(shù)還對數(shù)組進行元素操作,生成數(shù)組作為輸出。
注意: 我們上面使用重載運算符所做的所有操作都可以使用 ufunc 完成,例如 np.add、np.subtract、np.multiply、np.divide、np.sum 等。
# 在 numpy 中演示通用函數(shù)的 Python 程序
import numpy as np
# 創(chuàng)建一個正弦值數(shù)組
a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))
# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))
# square root of array values
print ("Square root of array elements:", np.sqrt(a))
輸出:
Sine values of array elements: [ ?0.00000000e+00 ? 1.00000000e+00 ? 1.22464680e-16]
Exponent of array elements: [ ?1. ? ? ? ? ? 2.71828183 ? 7.3890561 ? 20.08553692]
Square root of array elements: [ 0. ? ? ? ? ?1. ? ? ? ? ?1.41421356 ?1.73205081]
數(shù)據(jù)類型
每個 ndarray 都有一個關(guān)聯(lián)的數(shù)據(jù)類型 (dtype) 對象。這個數(shù)據(jù)類型對象(dtype)告訴我們數(shù)組的布局。這意味著它為我們提供了以下信息:
- 數(shù)據(jù)類型(整數(shù)、浮點數(shù)、Python 對象等)
- 數(shù)據(jù)大小(字節(jié)數(shù))
- 數(shù)據(jù)的字節(jié)順序(小端或大端)
- 如果數(shù)據(jù)類型是子數(shù)組,它的形狀和數(shù)據(jù)類型是什么。
ndarray的值存儲在緩沖區(qū)中,可以將其視為連續(xù)的內(nèi)存字節(jié)塊。所以這些字節(jié)將如何被解釋由 dtype 對象給出。
每個 Numpy 數(shù)組都是一個元素表(通常是數(shù)字),所有元素類型相同,由正整數(shù)元組索引。每個 ndarray 都有一個關(guān)聯(lián)的數(shù)據(jù)類型 (dtype) 對象。
此數(shù)據(jù)類型對象 (dtype) 提供有關(guān)數(shù)組布局的信息。ndarray 的值存儲在緩沖區(qū)中,可以將其視為可以由 dtype 對象解釋的連續(xù)內(nèi)存字節(jié)塊。Numpy 提供了大量可用于構(gòu)造數(shù)組的數(shù)值數(shù)據(jù)類型。
在創(chuàng)建數(shù)組時,Numpy 會嘗試猜測數(shù)據(jù)類型,但構(gòu)造數(shù)組的函數(shù)通常還包含一個可選參數(shù)來顯式指定數(shù)據(jù)類型。
# Python Program to create a data type object
import numpy as np
# np.int16 is converted into a data type object.
print(np.dtype(np.int16))
輸出:
int16
# Python Program to create a data type object
# containing a 32 bit big-endian integer
import numpy as np
# i4 represents integer of size 4 byte
# > represents big-endian byte ordering and
# < represents little-endian encoding.
# dt is a dtype object
dt = np.dtype('>i4')
print("Byte order is:",dt.byteorder)
print("Size is:",dt.itemsize)
print("Data type is:",dt.name)
輸出:
Byte order is: >
Size is: 4
Name of data type is: int32
原文鏈接:https://juejin.cn/post/7135688832124452894
相關(guān)推薦
- 2022-03-05 C#多線程用法詳解_C#教程
- 2022-07-18 Element-UI:el-table樣式修改
- 2022-10-04 淺析C++模板類型中的原樣轉(zhuǎn)發(fā)和可變參數(shù)的實現(xiàn)_C 語言
- 2024-01-06 RocketMQ重復(fù)消費問題
- 2022-09-30 Docker容器搭建本地私有倉庫詳情_docker
- 2022-08-14 hyper-v如何配置NAT網(wǎng)絡(luò)的實現(xiàn)_Hyper-V
- 2022-06-29 Python利用pynput實現(xiàn)劃詞復(fù)制功能_python
- 2022-09-17 C++?中如何結(jié)束?while?(cin>>str)?的輸入_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支