Python numpy ndarray屬性,索引,切片
一、ndarray 的重要屬性
- dtype屬性:返回ndarray數(shù)組的數(shù)據(jù)類型,數(shù)據(jù)類型的種類。
- ndim屬性:返回數(shù)組維度的數(shù)量。
- shape屬性:返回數(shù)組對象的尺度,對于矩陣,即n行m列,shape是一個元組(tuple)。
- size屬性:返回用來保存元素的數(shù)量,相當(dāng)于shape中n×m的值。
- T屬性:返回數(shù)組轉(zhuǎn)置。
二、切片
1. 一維切片
import numpy as np arr_1d = np.arange(12) arr_1d[:4] # 省卻起始,默認(rèn)從0開始 arr_1d[6:11] arr_1d[0:11:2] # 指定步長為 2 arr_1d[12:6:-1] # 反向切片
1. 二維切片
如果是多維數(shù)組,只需在每個維度之間用 ‘,’ 隔開。
import numpy as np arr_2d = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) arr_2d[0:2, 0:2] arr_2d[0:2, -3:] #前2行,倒數(shù)第3列開始 arr_2d[-2:, ::2] # 倒數(shù)第2行開始 列根據(jù)步長2,每隔一列取一列
三、索引
1. 一維數(shù)組索引
import numpy as np arr_1d = np.arange(12) arr_1d[4] arr_1d[-2] # 反向索引 arr_1d[[2,4,6,7,8,9]] # 同事索引多個
2. 二維數(shù)組索引
import numpy as np arr_2d = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) arr_2d[1, 2] arr_2d[-1, -1] # 反向索引 # 如果索引比維度少的多維數(shù)組,則會獲得一個子維數(shù)組 arr_2d[2] # 取 index=2 的行 # out array([ 7, 8, 9, 10]) arr_2d[2][0] # index=2 的行后,再去index=0 的列 # out 7 arr_2d[[2,0]] # 同時取 index =2 和 index=0 的行 # out array([[ 7, 8, 9, 10], [ 1, 2, 3, 4]])
3. 布爾索引
布爾索引就是根據(jù)條件篩選,判斷每個元素在條件下是True還是False,也就是布爾值,當(dāng)條件判斷True時,返回。當(dāng)條件判斷為False時,過濾掉。
import numpy as np arr_1d = np.arange(12) arr_1d[[False, False, False, False, False, True, True, True, True, True, True, True]] # out array([ 5, 6, 7, 8, 9, 10, 11]) arr_1d>=5 # out array([False, False, False, False, False, True, # True, True, True, True, True, True]) arr_1d[arr_1d>=5] # out array([ 5, 6, 7, 8, 9, 10, 11])
4. 非運算
arr_1d[~(arr_1d>=5)] # out array([0, 1, 2, 3, 4])
5. 或運算
只要對應(yīng)的二個二進位有一個為1時,結(jié)果位就為1。
arr_2d = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) (arr_2d>=8) | (arr_2d<=2) # out array([[ True, True, False, False], # [False, False, False, False], # [False, True, True, True]]) arr_2d[(arr_2d>=8) | (arr_2d<=2)] # out array([ 1, 2, 8, 9, 10])
6. 與運算
參與運算的兩個值,如果兩個相應(yīng)位都為1,則該位的結(jié)果為1,否則為0
arr_2d = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) arr_2d[(arr_2d<=8) & (arr_2d>=2)] # ount array([2, 3, 4, 4, 5, 6, 7, 7, 8])
到此這篇關(guān)于Python numpy ndarray屬性,索引,切片的文章就介紹到這了,更多相關(guān)Python numpy ndarray 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python緩存方案優(yōu)化程序性能提高數(shù)據(jù)訪問速度
Python緩存方案是一種優(yōu)化程序性能,提高數(shù)據(jù)訪問速度的方案。通過緩存數(shù)據(jù),可以減少重復(fù)的計算和IO操作,從而提高程序的運行效率。Python中常用的緩存方案包括內(nèi)存緩存、磁盤緩存和分布式緩存等,根據(jù)實際需求選擇不同的方案可以幫助我們更好地優(yōu)化程序性能2023-05-05python?selenium參數(shù)詳解和實現(xiàn)案例
這篇文章主要介紹了python?selenium參數(shù)詳解和實現(xiàn)案例,無頭模式添加,可以讓selenium模擬登錄,進入到后臺運行,本文以登錄打開公司內(nèi)網(wǎng)下載數(shù)據(jù)為例,給大家詳細(xì)講解,需要的朋友可以參考下2022-10-10Python中Numpy與TensorFlow版本兼容問題完美解決辦法
這篇文章主要給大家介紹了關(guān)于Python中Numpy與TensorFlow版本兼容問題的完美解決辦法,確保Python版本與TensorFlow版本兼容是首要任務(wù),因為不兼容的組合可能導(dǎo)致導(dǎo)入錯誤或其他運行時問題,需要的朋友可以參考下2024-07-07