2

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?

0

3 Answers 3

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

This might help
1

Try this:

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

1 Comment

As I mentioned in the question "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?"
0

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]

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.