[英]How does numpy's indexing work in this scenario
plot numpy的逻辑索引如何从下面的代码片段中的“data”变量中获取数据点? 我知道第一个参数是x坐标,第二个参数是y坐标。 我不确定它如何映射到变量的数据点。
data = vstack((rand(150,2) + array([.5,.5]),rand(150,2)))
# assign each sample to a cluster
idx,_ = vq(data,centroids)
# some plotting using numpy's logical indexing
plot(data[idx==0,0],data[idx==0,1],'ob',
data[idx==1,0],data[idx==1,1],'or')
plot(centroids[:,0],centroids[:,1],'sg',markersize=8)
它的形状都是:
In [89]: data.shape
Out[89]: (300, 2) # data has 300 rows and 2 columns
In [93]: idx.shape
Out[93]: (300,) # idx is a 1D-array with 300 elements
idx == 0
是一个布尔数组,其形状与idx
相同。 只要idx
的元素等于0
它就是True
:
In [97]: (idx==0).shape
Out[97]: (300,)
当您使用idx==0
索引data
时,您将获得idx==0
为True的所有data
行:
In [98]: data[idx==0].shape
Out[98]: (178, 2)
当您使用元组, data[idx==0, 0]
进行索引时,第一个data
轴使用布尔数组idx==0
进行索引,第二个data
轴使用0
索引:
In [99]: data[idx==0, 0].shape
Out[99]: (178,)
第一个data
轴对应行,第二个轴对应列。 所以你只得到第一列data[idx==0]
。 由于第一列data
是x
,因此在data
中给出了这些x
,其中idx==0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.