Robbie Mallett
Robbie Mallett

Reputation: 183

Get 1d numpy array from 2d array using list of indices

I have a 2d array (n x m) from which I would like to produce a 1d array (length n) using a list of row-indices of length n.

For instance:


2d = ([a,b,c],[d,e,f],[g,h,i]) # input array
1d = ([0,2,1]) # row numbers

result = ([a,e,h]) # array of the first row of first column, third row of second column, second row of third column


I have found a way to do this using a list comprehension (iterating over the columns and the indices simultaneously and picking out the value), but there's surely a numpy function that does this?

Upvotes: 2

Views: 1149

Answers (3)

BatWannaBe
BatWannaBe

Reputation: 4510

Specifying multiple elements by their indices and putting them in a new array is called "advanced indexing".

x = np.array([x for x in 'abcdefghi']).reshape((3,3))

# array([['a', 'b', 'c'],
#        ['d', 'e', 'f'],
#        ['g', 'h', 'i']], dtype='<U1')

d1_indices = np.array([0,1,2])
d2_indices = np.array([0,2,1])

selectx = x[d1_indices, d2_indices]
# array(['a', 'f', 'h'], dtype='<U1')

# selectx[i] = x[d1_indices[i], d2_indices[i]]

Upvotes: 1

tpl
tpl

Reputation: 327

How about this?

import numpy as np
a = np.arange(9).reshape((3,3))
# [0, 1, 2]
# [3, 4, 5]
# [6, 7, 8]
print(a[[0,2,1], np.arange(3)]) # result : [0 7 5]

Iterating by rows and picking a value based on column index is also possible:

print(a[np.arange(3),[0,2,1]]) # result : [0 5 7]

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

Try this:

print([y[x] for x, y in zip(_1d, _2d)])

Upvotes: 1

Related Questions