You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:15:54