21

I have an array :

e = np.array([[ 0,  1,  2,  3, 5, 6, 7, 8],
              [ 4,  5,  6,  7, 5, 3, 2, 5],
              [ 8,  9, 10, 11, 4, 5, 3, 5]])

I want to extract array by its columns in RANGE, if I want to take column in range 1 until 5, It will return

e = np.array([[ 1,  2,  3, 5, ],
              [ 5,  6,  7, 5, ],
              [ 9, 10, 11, 4, ]])

How to solve it? Thanks

3 Answers 3

37

You can just use e[:, 1:5] to retrive what you want.

In [1]: import numpy as np

In [2]: e = np.array([[ 0,  1,  2,  3, 5, 6, 7, 8],
   ...:               [ 4,  5,  6,  7, 5, 3, 2, 5],
   ...:               [ 8,  9, 10, 11, 4, 5, 3, 5]])

In [3]: e[:, 1:5]
Out[3]:
array([[ 1,  2,  3,  5],
       [ 5,  6,  7,  5],
       [ 9, 10, 11,  4]])

https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean e[:, 1:5].
If the array consists of decimal nos. and I wish to retrieve e[:, 1.1:5.2] i.e extract data-set inbetween 1.1 to 5.2 and its values in corresponding columns, how do we do that?
What if I want to select to ranges; let's say columns 1:3 and 5:7?
5

Numpy row and column indices start counting at 0.

The rows are specified first and then the column with a comma to separate the row from column.

The ":" (colon) is used to shortcut all rows or all columns when it is used alone.

When the row or column specifier has a range, then the ":" is paired with numbers that specify the inclusive start range and the exclusive end range.

For example

import numpy as np
np_array = np.array( [ [ 1, 2, 3, ],
                       [ 4, 5, 6, ],
                       [ 7, 8, 9  ] ]  )

first_row = np_array[0,:]
first_row
output: array([1, 2, 3])

last_column = np_array[:,2]
last_column
output: array([3, 6, 9])

first_two_vals = np_array[0,0:2]
first_two_vals
output: array([1, 2])

Comments

1

You can use np.take with specifying axis=1

import numpy as np
e = np.array([[ 0,  1,  2,  3, 5, 6, 7, 8],
              [ 4,  5,  6,  7, 5, 3, 2, 5],
              [ 8,  9, 10, 11, 4, 5, 3, 5]])
e = np.take(e, [1,2,3,4], axis=1)

output:
array([[ 1,  2,  3,  5],
       [ 5,  6,  7,  5],
       [ 9, 10, 11,  4]])

https://numpy.org/doc/stable/reference/generated/numpy.take.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.