網站首頁 編程語言 正文
前言
NumPy(Numerical Python的縮寫)是一個開源的Python科學計算庫。使用NumPy,就可以很自然地使用數組和矩陣。NumPy包含很多實用的數學函數,涵蓋線性代數運算、傅里葉變換和隨機數生成等功能。本文主要介紹Python NumPy 數組索引及訪問數組元素。
1、訪問數組元素
數組索引與訪問數組元素相同。
您可以通過引用其索引號來訪問數組元素。
NumPy數組中的索引以0開頭,這意味著第一個元素的索引為0,第二個元素的索引為1等。
例如:
從以下數組中獲取第一個元素:
import numpy as np
arr = np.array([1, 3, 3, 4])
print(arr[0])
# 1
例如:
從以下數組中獲取第二個元素。
import numpy as np
arr = np.array([1, 3, 3, 4])
print(arr[1])
# 3
例如:
從以下數組中獲取第三和第四個元素并將其添加。
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])
# 7
2、訪問 2-D Arrays(數組)
要訪問二維數組中的元素,我們可以使用逗號分隔的整數來表示元素的維數和索引。
例如:
在第一個昏暗處訪問第二個元素:
import numpy as np
arr = np.array([[1,12,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st dim: ', arr[0, 1])
# 2nd element on 1st dim: 12
例如:
進入第二個暗處的第五個元素:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,110]])
print('5th element on 2nd dim: ', arr[1, 4])
# 5th element on 2nd dim: 110
3、訪問 3-D Arrays(數組)
要訪問3-D數組中的元素,我們可以使用逗號分隔的整數來表示元素的尺寸和索引。
例如:
訪問第一個數組的第二個數組的第三個元素:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
示例說明
arr[0, 1, 2]輸出的值為6.
這就是為什么:
第一個數字表示第一維,它包含兩個數組:
[[1、2、3],[4、5、6]]
和:
[[7、8, 9],[10,11,12]]
因為我們選擇了0,所以剩下的第一個數組是:
[[1、2、3],[4 ,5,6]]
第二個數字代表第二維,它還包含兩個數組:
[1、2、3]
和:
[4、5、6]
,因為我們選擇了1,剩下第二個數組:
[4,5,6]
第三個數字代表第三個維度,其中包含三個值:
4
5
6
由于我們選擇了2,因此我們以第三個維度結束 值:
6
4、負索引
使用負索引從頭開始訪問數組。
例如:
打印第二個暗處的最后一個元素:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,110]])
print('Last element from 2nd dim: ', arr[1, -1])
# Last element from 2nd dim: 110
參考資料:https://www.cjavapy.com/article/1040/
原文鏈接:https://blog.csdn.net/weixin_64338372/article/details/128658908
相關推薦
- 2022-03-01 iview表格中 colums中使用render函數的幾種總結
- 2022-03-24 C語言函數指針詳解_C 語言
- 2022-10-07 react性能優化useMemo與useCallback使用對比詳解_React
- 2022-12-29 解決React報錯Expected?`onClick`?listener?to?be?a?funct
- 2023-12-16 SpringBoot 配置文件使用@ @取值
- 2022-01-12 2022年了--你還不會手寫promise? --_-- promise的實現 第一版
- 2022-06-30 Oracle在PL/SQL中使用子查詢_oracle
- 2022-03-23 Android應用內懸浮窗Activity的簡單實現_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支