gpt4 book ai didi

python - 将数字映射到 python 中的 id

转载 作者:行者123 更新时间:2023-11-28 20:39:29 25 4
gpt4 key购买 nike

假设我有一个像这样的 numpy 数组:[11, 30, 25]。这些数字表示对应于索引的对象类别。我知道只有 20 个类别,但出于某种原因,它们的编号从 11 到 29。我想将它们转换为 0:19 中的数字,然后返回。 pythonic 的方式会怎样做呢?最好是颠簸。

编辑:这只是一个更大问题的一个小例子,其中类别的数量为数千,并且一些类别从未被表示过,因此最大 id 将是唯一的现有类别的数量。

最佳答案

假设 arr 是类别的输入数组。

前向处理/编码:从类别到 ID

要执行编码,请使用 np.unique 及其可选的 return_inverse 参数为我们提供值从 0N-1,其中 N 是您在 arr 中拥有的类别数,就像这样 -

unq,idx = np.unique(arr,return_inverse=True)

反向处理/解码:从 ID 到类别

要从 ID (idx) 返回到原始类别,只需索引到之前保存为 unq 的唯一类别,就像这样 -

arr_out = unq[idx]

sample 运行-

In [40]: arr # Input array of categories
Out[40]: array([7, 1, 1, 3, 8, 2, 7, 7, 0, 2])

In [41]: unq,idx = np.unique(arr,return_inverse=True)

In [42]: idx # ID array with values from 0 to 5 (6 categories)
Out[42]: array([4, 1, 1, 3, 5, 2, 4, 4, 0, 2])

In [43]: unq[idx] # Get back original array of categories
Out[43]: array([7, 1, 1, 3, 8, 2, 7, 7, 0, 2])

关于python - 将数字映射到 python 中的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38109760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com