Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy - select multiple elements from each row of an array

Tags:

python

numpy

I need to select multiple different values from each row of a 2D array.

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

>>> np.array([[ 1, 2],
              [ 6, 7],
              [11,12]])

I know I can create a boolean array the same shape as A and set each element in a for loop, but I'm hoping come up with a better solution.

like image 811
phsyron Avatar asked Jun 10 '18 20:06

phsyron


People also ask

How do I select part of a NumPy array?

Slice a Range of Values from Two-dimensional Numpy Arrays For example, you can use the index [0:1, 0:2] to select the elements in first row, first two columns. You can flip these index values to select elements in the first two rows, first column.

What does .all do in NumPy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.


1 Answers

You can try the following:

import numpy as np
A = np.array([[ 1, 2, 3, 4],
              [ 5, 6, 7, 8],
              [ 9,10,11,12]])
i = [[0],[1],[2]]
j = [[0,1], [1,2],[2,3]]
B = A[i,j]
print(B)
#Prints
[[ 1  2]
 [ 6  7]
 [11 12]]

Example run

like image 142
Md Johirul Islam Avatar answered Nov 14 '22 22:11

Md Johirul Islam