Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

Some array indexing in numpy

    lookup = np.array([60, 40, 50, 60, 90])

The values in the following arrays are equal to indices of lookup.

    a = np.array([1, 2, 0, 4, 3, 2, 4, 2, 0])
    b = np.array([0, 1, 2, 3, 3, 4, 1, 2, 1])
    c = np.array([4, 2, 1, 4, 4, 0, 4, 4, 2])

    array       1st column elements             lookup value

    a            1        -->                   40
    b            0        -->                   60
    c            4        -->                   90

Maximum is 90.

So, first element of result is 4.

This way,

expected result = array([4, 2, 0, 4, 4, 4, 4, 4, 0])

How to get it?

I tried as:

d = np.vstack([a, b, c])

print (d)

res = lookup[d]

res = np.max(res, axis = 0)

print (d[enumerate(lookup)])

I got error

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you want this:

d = np.vstack([a,b,c])

# option 1
rows = lookup[d].argmax(0)
d[rows, np.arange(d.shape[1])]

# option 2
(lookup[:,None] == lookup[d].max(0)).argmax(0)

Output:

array([4, 2, 0, 4, 4, 4, 4, 4, 0])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...