numpy boolean indexing confusion

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

Hello could someone explain how is the following code working? After importing the required libraries..

>>>features=np.random.rand(150,4) >>>features= np.append(features,np.random.randint(3,size=(150,1)),axis=1) >>>target=np.array([0,1,2]) >>>plt.scatter(features[target == 1,0], features[target == 1,1], marker='o', c='r') 

I am getting a plot of 1st and 2nd column of 'features' having 1 in the last column. But I am not able to understand how.

As far as I can understand 'target==1' creates a boolean array but how can it return values of the 1st and 2nd columns when there is no value representing 1 in those columns.

Does numpy indexing search values from all columns?

回答1:

Say you have a matrix and a vector:

A =np.array([[1,2,3],     [4,5,6]])  b = np.array([0, 1, 2]) 

And you do the following:

A[b==1,2] # will return 6 

This tells python you want the row index where b==1 (ie 1) and you want the column index of 2 in the matrix A.

Another example:

A[b==0,1] # will return 2 

Similarly, in your example, you are finding scalar values.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!