我正在尝试完成以下任务,但没有循环/列表理解
count = np.array([np.sum(X[Z==k],axis=0) for k in range(num_clusters)])
X是二维数组,Z是一维数组,值从0到k。
在此先感谢您的帮助!
示例数据:
num_clusters = 5
num_datapoints = 100
X = np.random.choice(20,[num_datapoints,15])
# Example data matrix of shape (num_datapoints,15) where each of the 15 "features" can have a value from 0 to 20.
Z = np.random.choice(num_clusters,num_datapoints) # random cluster assignments for 100 datapoints
count = np.array([np.sum(X[Z==k],axis=0) for k in range(num_clusters)])
结果:
array([[171,178,148,136,100,108,125,158,135,118,133,149,143,112,198],[226,181,199,220,186,193,217,230,234,194,170,227,241,245,161],[160,171,126,156,152,164,134,128,224,173,213,166,178],[162,161,229,216,182,168,155,188,187,210,219,158],[188,233,244,222,232,307,265,239,189,253,259,212]])