繁体   English   中英

numpy的索引如何在这种情况下工作

[英]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] 由于第一列datax ,因此在data中给出了这些x ,其中idx==0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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