Python 计算Numpy矩阵中每行的平均值
我想实现phython代码,该代码执行以下操作:Python 计算Numpy矩阵中每行的平均值,python,numpy,mean,Python,Numpy,Mean,我想实现phython代码,该代码执行以下操作: For a collections of clusters calculate the mean for each cluster Args: clusters (List[np.ndarray]): A list of 2d arrays Returns: List[np.ndarray]: A matrix where each row represents a mean of a cluster Ex
For a collections of clusters calculate the mean for each cluster
Args:
clusters (List[np.ndarray]): A list of 2d arrays
Returns:
List[np.ndarray]: A matrix where each row represents a mean of a cluster
Example:
>>> tiny_clusters = [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
]
>>> calc_means(tiny_clusters)
[array([0.15, 0.25]), array([0.7,0.7])]
i = 0
return [clusters[i].mean(axis=1) for i in range(np.amax(i)+1)]
我目前的解决方案如下:
For a collections of clusters calculate the mean for each cluster
Args:
clusters (List[np.ndarray]): A list of 2d arrays
Returns:
List[np.ndarray]: A matrix where each row represents a mean of a cluster
Example:
>>> tiny_clusters = [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
]
>>> calc_means(tiny_clusters)
[array([0.15, 0.25]), array([0.7,0.7])]
i = 0
return [clusters[i].mean(axis=1) for i in range(np.amax(i)+1)]
但是,我只得到以下输出:
[array([0.25, 0.15])]
(Input: [
np.array([[0.2, 0.3], [0.1, 0.2]]),
np.array([[0.8, 0.9], [0.7, 0.5], [0.6, 0.7]]),
])
因此,我只计算了第一行的平均值,但不幸的是,第二行的平均值没有计算出来。你知道哪些改进了我的代码吗
谢谢 列表理解应该是
[q.mean(axis=0) for q in clusters]
将输出称为矩阵有点令人困惑。这是排名1的数组列表。列表应为
[q.mean(axis=0) for q in clusters]
将输出称为矩阵有点令人困惑。这是一个排名1的数组列表。不要给所有数组命名
i
。不要给所有数组命名i
。可能是我写的。。。对于集群中的集群
,没问题,可能是我写的。。。对于集群中的集群
,但这是可以的