如何将np.unique返回结果转换为(label, n_samples)格式的元组列表?
解决方法
你可以利用Python内置的zip()函数实现需求——它会将np.unique返回的标签数组和计数数组按位置一一配对,再通过list()将配对结果转换为列表即可。
完整代码示例
import numpy as np # 原始标签数组 y = np.array([3, 3, 3, 2, 3, 1, 3, 2, 3, 3, 3, 2, 2, 3, 2]) # 获取标签和对应样本数 labels, counts = np.unique(y, return_counts=True) # 转换为(label, n_samples)格式的元组列表 label_count_list = list(zip(labels, counts)) print(label_count_list)
输出结果
[(1, 1), (2, 5), (3, 9)]
如果偏好列表推导式,也可以用以下写法,效果完全一致:
label_count_list = [(labels[i], counts[i]) for i in range(len(labels))]
内容的提问来源于stack exchange,提问作者Amina Umar
相关产品推荐
相关产品推荐

