Python numpy和#x27;在这种情况下,我们需要进行索引工作
plot numpy的逻辑索引是如何从下面代码段中的“data”变量中获取数据点的?我知道第一个参数是x坐标,第二个参数是y坐标。我不确定它如何从变量映射到数据点Python numpy和#x27;在这种情况下,我们需要进行索引工作,python,numpy,matplotlib,Python,Numpy,Matplotlib,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 p
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,)
In [99]: data[idx==0, 0].shape
Out[99]: (178,)
当您使用idx==0
索引data
时,您将获得数据的所有行,其中idx==0
为真:
In [98]: data[idx==0].shape
Out[98]: (178, 2)
当使用元组进行索引时,data[idx==0,0]
,data
的第一轴使用布尔数组idx==0
进行索引,而data
的第二轴使用0
进行索引:
In [97]: (idx==0).shape
Out[97]: (300,)
In [99]: data[idx==0, 0].shape
Out[99]: (178,)
数据的第一个轴对应于行,第二个轴对应于列。因此,您只得到数据[idx==0]
的第一列。由于数据
的第一列是x
-值,这将为您提供data
中的x
-值,其中idx==0