gpt4 book ai didi

python - 如何将一系列索引/类别转换为分类数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:45 25 4
gpt4 key购买 nike

如何将一系列索引转换为二维数组,该数组表示由列表中的索引值定义的类别/分类器?

例如:

import numpy as np

aList = [0,1,0,2]
anArray = np.array(aList)

resultArray = convertToCategories(anArray)

convertToCategories() 的返回值如下:

[[1,0,0],             # the 0th element of aList is index category 0
[0,1,0], # the 1st element of aList is index category 1
[1,0,0], # the 2nd element of aList is index category 0
[0,0,1]] # the 3rd element of aList is index category 2

最后,我当然可以:

  • 解析列表,
  • 计算类别的数量(它是连续的/连续的,可以简单地找到最大值)
  • 创建一个大小合适的归零数组
  • 然后重新解析列表,根据列表给定的索引用1(或True)填充数组。

但我想知道是否存在更 pythonic 或专用的 numpy 或 pandas 函数来实现这种转换。

最佳答案

你可以这样做 -

import numpy as np

# Size parameters
N = anArray.size
M = anArray.max()+1

# Setup output array
resultArray = np.zeros((N,M),int)

# Find out the linear indices where 1s would be put
idx = (np.arange(N)*M) + anArray

# Finally, put 1s at those places for the final output
resultArray.ravel()[idx] = 1

sample 运行-

In [188]: anArray
Out[188]: array([0, 1, 0, 2, 4, 1, 3])

In [189]: resultArray
Out[189]:
array([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0]])

或者,最好直接使用行和列索引索引到输出数组中 -

# Setup output array and put 1s at places indexed by row and column indices.
# Here, anArray would be the column indices and [0,1,....N-1] would be the row indices
resultArray = np.zeros((N,M),int)
resultArray[np.arange(N),anArray] = 1

关于python - 如何将一系列索引/类别转换为分类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016014/

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