Combine Selection Conditions

I would like to combine several conditions to select row / columns from an array.

Given the matrix A, I know that

A[:, [1,3]] 

gives me the second and fourth columns. Besides,

A[:, :3]

works like a charm. However, I cannot combine the conditions:

A[:, [:3, 6, 7]]

gives a syntax error. How can I get this choice?

+4
source share
2 answers

In a nutshell you can:

A[:, range(3) + [6, 7]]

or

A[:, np.r_[:3, 6, 7]]

To understand why your first attempt did not work, you need to understand a little more about how general python indexing is and how numpy is indexed.


-, , blah = [:3, 6, 7] python, . ( A[:, [:3, 6, 7]]. .) Numpy ( ) , - , : np.r_. :

In [1]: print np.r_[:3, 6, 7]
[0 1 2 6 7]

, (np.r_ , list), :

In [2]: print range(3) + [6, 7]
[0, 1, 2, 6, 7]

, numpy. numpy. "" . . "" (, ) .

, , (.. , ), . ( " " Numpy. " " , " 2, 5 6", ).

, , . ( ) :

In [1]: a = np.arange(18).reshape(3, 6)

In [2]: a
Out[2]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

In [3]: b = a[:, :3]

In [4]: b
Out[4]:
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])

In [5]: c = a[:, [0, 1, 2]]

In [6]: c
Out[6]:
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])

b c . c - a, b - . c, a :

In [7]: c[0, 0] = 10000

In [8]: c
Out[8]:
array([[10000,     1,     2],
       [    6,     7,     8],
       [   12,    13,    14]])

In [9]: a
Out[9]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

b, a :

In [10]: a
Out[10]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

In [11]: b[0,0] = 99999

In [12]: a
Out[12]:
array([[99999,     1,     2,     3,     4,     5],
       [    6,     7,     8,     9,    10,    11],
       [   12,    13,    14,    15,    16,    17]])

In [13]: b
Out[13]:
array([[99999,     1,     2],
       [    6,     7,     8],
       [   12,    13,    14]])

numpy ( , .). , , .

+5

, , :

>>> A = numpy.array([range(10)]*10)
>>> numpy.hstack((A[:, :3],A[:, [6,7]]))
array([[0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7],
       [0, 1, 2, 6, 7]])
>>> 
0

All Articles