AAA
AAA

Reputation: 305

How to return some column items in a NumPy array?

I want print some items in 2D NumPy array.

For example:

a = [[1, 2, 3, 4],
     [5, 6, 7, 8]]

a = numpy.array(a)

My questions:

  1. How can I return just (1 and 2)? As well as (5 and 6)?
  2. And how can I keep the dimension as [2, 2]

Upvotes: 0

Views: 64

Answers (3)

Rahul K P
Rahul K P

Reputation: 16081

You can do like this,

In [44]: a[:, :2]
Out[44]: 
array([[1, 2],
       [5, 6]])

Upvotes: 1

Asterisk
Asterisk

Reputation: 3574

You can use slicing to get necessary parts of the numpy array. To get 1 and 2 you need to select 0's row and the first two columns, i.e.

>>> a[0, 0:2]
array([1, 2])

Similarly for 5 and 6

>>> a[1, 0:2]
array([5, 6])

You can also select a 2x2 subarray, e.g.

>>> a[:,0:2]
array([[1, 2],
       [5, 6]])

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20015

The following:

a[:, [0, 1]]

will select only the first two columns (with index 0 and 1). The result will be:

array([[1, 2],
       [5, 6]])

Upvotes: 2

Related Questions