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

如何为Numpy数组中的唯一值生成对应的整数索引

Numpy 元素映射为专属整数的修改方案

方案1:基于原有代码最小改动

你现有代码每次循环生成的是仅当前类别位置为对应编号、其余位置为0的数组,直接累计赋值即可实现需求,修改后代码如下:

import numpy as np

array1 = np.array(['dog', 'cat', 'parrot', 'parrot', 'dog'])
array2 = np.unique(array1)
# 初始化和输入数组等长的全0结果数组
result = np.zeros(len(array1), dtype=int)
for index, key in enumerate(array2):
    result[array1 == key] = index + 1
print(result)

运行后直接输出目标结果:[1 2 3 3 1]

方案2:更高效的原生API实现

Numpy 的 np.unique 本身支持返回原数组元素对应唯一值的索引,无需手动编写循环,性能更优,大数据量场景更推荐使用:

import numpy as np

array1 = np.array(['dog', 'cat', 'parrot', 'parrot', 'dog'])
# return_inverse 参数开启后会返回原数组每个元素对应唯一值的下标
_, idx = np.unique(array1, return_inverse=True)
# 下标默认从0开始,加1即可得到1开头的专属编号
result = idx + 1
print(result)

内容的提问来源于stack exchange,提问作者Amateur1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:45:04