4

plot numpy 的逻辑索引如何从下面代码片段中的“数据”变量中获取数据点?我知道第一个参数是 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)
4

1 回答 1

4

这一切都在形状中:

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。它是equalsTrue中的元素:idx0

In [97]: (idx==0).shape
Out[97]: (300,)

当您使用 索引dataidx==0,您将获得datawhereidx==0为 True 的所有行:

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-values,这会为您提供where 中的那些x-values 。dataidx==0

于 2013-07-28T00:19:43.013 回答