为每行选择不同的列

时间:2017-11-15 14:41:35

标签: python numpy

假设我有以下数组:

@media screen and (max-width:732px) and (min-width:425px) {
.logo-svrs {
    position: relative !important;
    display: block !important;
    width: 114px;
    height: 29.5px;
    margin: 0 auto;
    z-index: 9999;
    border: solid #ff0000 3px !important;
    overflow: visible !important;
 }
.header {  
    display: visible;
}
.bg-banner {
    position: absolute !important;
    background-image: url(../imgs/apply_header.jpg) !important;
    background-repeat: no-repeat;
    background-size: 100% 40% !important; 
    z-index: 0;
}
.notices {
    position: relative !important;
    width: 370px !important;
    height: 350px !important;
    text-align: center;
    margin: 0 auto;
    margin-top: 200px !important;
    z-index: 9999;
    border-radius: 5px !important;
    box-shadow:  0 0 10px  rgba(0,0,0,0.5) !important;
    -moz-box-shadow: 0 0 10px  rgba(0,0,0,0.5) !important;
    -webkit-box-shadow: 0 0 10px  rgba(0,0,0,0.5) !important;
    -o-box-shadow: 0 0 10px  rgba(0,0,0,0.5) !important;
}

现在我想根据以下索引数组为每一行选择不同的列:

>>> a = np.arange(25).reshape((5, 5))
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

此索引数组表示每行的 start 列,并且选择应具有相似的范围,例如:因此,我希望得到以下结果:

>>> i = np.array([0, 1, 2, 1, 0])

我知道我可以通过

选择每行一列
>>> ???
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14],
       [16, 17, 18],
       [20, 21, 22]])

但多列怎么样?

1 个答案:

答案 0 :(得分:4)

advanced indexing与正确广播的2d数组一起用作索引。

a[np.arange(a.shape[0])[:,None], i[:,None] + np.arange(3)]
#array([[ 0,  1,  2],
#       [ 6,  7,  8],
#       [12, 13, 14],
#       [16, 17, 18],
#       [20, 21, 22]])
idx_row = np.arange(a.shape[0])[:,None]
idx_col = i[:,None] + np.arange(3)

idx_row
#array([[0],
#       [1],
#       [2],
#       [3],
#       [4]])

idx_col
#array([[0, 1, 2],
#       [1, 2, 3],
#       [2, 3, 4],
#       [1, 2, 3],
#       [0, 1, 2]])

a[idx_row, idx_col]
#array([[ 0,  1,  2],
#       [ 6,  7,  8],
#       [12, 13, 14],
#       [16, 17, 18],
#       [20, 21, 22]])