简体   繁体   中英

Don't understand how this numpy operation works for two arrays

I see by exercising the below code is working but don't figure out why? This is using python numpy.

The first code snippet shows I have one dimension numpy array c, a two dimension numpy array b, with c's values are within the range of the row number of b, then b[c] is working and we get an expanded array.

import numpy as np
c=np.array([2,3,4,5,1,4,3,4,3,1,4,3,4,1,4,5])
print("c is\n",c)
print("=========================")
b=np.random.rand(6,3)
print("b is\n ",b)
print("=========================")
print("b[c] is\n",b[c])

c is
 [2 3 4 5 1 4 3 4 3 1 4 3 4 1 4 5]
=========================
b is
  [[0.85983145 0.25222867 0.02340111]
 [0.82655905 0.80128734 0.83493173]
 [0.01817893 0.64987559 0.4190797 ]
 [0.10836948 0.40150688 0.59126363]
 [0.59367641 0.38069116 0.82918134]
 [0.02770242 0.62288968 0.46228432]]
=========================
b[c] is
 [[0.01817893 0.64987559 0.4190797 ]
 [0.10836948 0.40150688 0.59126363]
 [0.59367641 0.38069116 0.82918134]
 [0.02770242 0.62288968 0.46228432]
 [0.82655905 0.80128734 0.83493173]
 [0.59367641 0.38069116 0.82918134]
 [0.10836948 0.40150688 0.59126363]
 [0.59367641 0.38069116 0.82918134]
 [0.10836948 0.40150688 0.59126363]
 [0.82655905 0.80128734 0.83493173]
 [0.59367641 0.38069116 0.82918134]
 [0.10836948 0.40150688 0.59126363]
 [0.59367641 0.38069116 0.82918134]
 [0.82655905 0.80128734 0.83493173]
 [0.59367641 0.38069116 0.82918134]
 [0.02770242 0.62288968 0.46228432]]

However, if I change the same to list as below, it will not work:

>>> a=[[3,4,3],[4,5,3],[3,4,2]]
>>> b=[2,3,2,1]
>>> a[b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not list

What is the difference? What's the operation called in numpy? I can't find out. Thank you!

With

b=np.random.rand(6,3)
c=np.array([2,3,4,5,1,4,3,4,3,1,4,3,4,1,4,5])
b[c]

you use Numpy's integer array indexing to pluck values at given offsets.

That's simply not a thing with regular Python lists. If you wanted to emulate something similar, you'd do

a = [[3,4,3],[4,5,3],[3,4,2]]
b = [2,3,2,1]
c = [a[i] for i in b]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM