欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的numpy選擇特定行列的方法

 更新時間:2023年08月24日 10:39:42   作者:goodxin_ie  
這篇文章主要介紹了Python的numpy選擇特定行列的方法,有時需要抽取矩陣中特定行的特定列,比如,需要抽取矩陣x的0,1行的0,3列,結(jié)果為矩陣域,需要的朋友可以參考下

numpy選擇特定行列

有時需要抽取矩陣中特定行的特定列。

比如,需要抽取矩陣x的0,1行的0,3列,結(jié)果為矩陣域

x = np.array([[ 0,  1,  2,  3],
               [ 4,  5,  6,  7],
               [ 8,  9, 10, 11],
               [12, 13, 14, 15]])
y = np.array([[ 0,  3],
              [ 4,  7]])

錯誤做法:第一反應(yīng)這樣寫x[[0,1],[0,3]],然而得到的結(jié)果為

y
Out[22]: array([0, 7])

其實這種寫法是抽去了[0,0],[1,3]兩個位置的數(shù)。numpy的所有維度的坐標(biāo)個數(shù)應(yīng)該相等,且互相是配對的。

Numpy數(shù)組的整數(shù)數(shù)組索引,返回數(shù)據(jù)副本,而不是創(chuàng)建視圖。相比切片索引,整數(shù)數(shù)組的索引更具有通用性,因為其不要求索引值具有特定規(guī)律。

整數(shù)數(shù)組索引要點如下:

  • 對于索引數(shù)組中未建立索引的維度(索引數(shù)組中的索引集數(shù)目小于被索引數(shù)組維度),默認(rèn)被全部索引;
  • 索引結(jié)果數(shù)組的形狀由索引數(shù)組的形狀與被索引數(shù)組中所有未索引的維的形狀串聯(lián)組成,也就是說,若對數(shù)組的所有維度建立索引,則索引數(shù)組的形狀等于結(jié)果數(shù)組的形狀;
  • 若索引數(shù)組具有匹配的形狀,即索引數(shù)組個數(shù)(索引集數(shù))等于被索引數(shù)組的維度,此時結(jié)果數(shù)組與索引數(shù)組具有相同形狀,且這些結(jié)果值對應(yīng)于各維索引集的索引在索引數(shù)組中的位置;

正確的做法有以下幾種:

1、先抽取行,再抽取列

 x[[0,1]][:,[0,3]]
Out[31]: 
array([[0, 3],
       [4, 7]])

2、由于結(jié)果數(shù)組與索引數(shù)組具有相同形狀,且這些結(jié)果值對應(yīng)于各維索引集的索引在索引數(shù)組中的位置,因此可以直接寫目標(biāo)數(shù)據(jù)的坐標(biāo)

index = [[[0,0],[1,1]],[[0,3],[0,3]]]
x[index]
Out[33]: 
array([[0, 3],
       [4, 7]])

此種做法也可以利用numpy的廣播機(jī)制,寫為

x[[0,1],[[0],[3]]]
Out[39]: 
array([[0, 4],
       [3, 7]])

注意與開始的錯誤寫法對比

3、Numpy提供的函數(shù) ix_() 更快地實現(xiàn)索引指定行列

ix_(*args)
    Construct an open mesh from multiple sequences.
    This function takes N 1-D sequences and returns N outputs with N
    dimensions each, such that the shape is 1 in all but one dimension
    and the dimension with the non-unit shape value cycles through all
    N dimensions.
    Using `ix_` one can quickly construct index arrays that will index
    the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
    ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.

寫法為:

i,j = np.ix_([0,1],[0,3]) 
x[i,j]
Out[44]: 
array([[0, 3],
       [4, 7]])

到此這篇關(guān)于Python的numpy選擇特定行列的方法的文章就介紹到這了,更多相關(guān)numpy選擇特定行列內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論