检查2d数组的每一行中不同列索引的2d数组的值

时间:2016-07-18 18:37:43

标签: python arrays numpy multidimensional-array

我有一些二进制2D numpy数组(prediction),如:

[
[1 0 1 0 1 1],
[0 0 1 0 0 1],
[1 1 1 1 1 0],
[1 1 0 0 1 1],
]

2D阵列中的每一行是将句子分类为特定类别,并且2D阵列中的每列对应于该句子的类别的分类。类别(categories数组)以['A','B','C','D','E','F']为例。

我有另一个2D数组(catIndex),其中包含要在每行中检查的值的索引,例如

[[0],
  [4],
  [5],
  [2]
] 

对于上述4个实例。

我想要做的是现在遍历二进制2D数组和为每个句子指定的列索引,检查它是1还是0,然后附加相应的类别到一个新的数组(catResult = [])。如果是0,我会将"no_region"附加到新数组。

例如,在句子1中,我查看句子的索引0,并检查它是0还是1。它是1,因此我将'A'附加到我的新数组中。在第2句中,我查看句子的索引4,并看到它是0,因此我将"no_region"附加到数组中。

当前代码:

for index in catIndex:
        for i,sentence in enumerate(prediction):
            for j,binaryLabel in enumerate(sentence):
                if prediction[i][index]==1:
                    catResult.append(categories[index])
                else:
                    catResult.append("no_region")

2 个答案:

答案 0 :(得分:1)

制作二维数组:

HighLightNearbyDots()

带有In [54]: M=[[1,0,1,0,1,1],[0,0,1,0,0,1],[1,1,1,1,1,0],[1,1,0,0,1,1]] In [55]: M=np.array(M) 的列索引,其中[0,1,2,3]为行索引:

ind

使用In [56]: ind=[0,4,5,2] In [57]: m=M[np.arange(len(ind)),ind] In [58]: m Out[58]: array([1, 0, 0, 0]) 映射标签:

ind

使用In [59]: lbl=np.array(list('ABCDEF'),dtype=object) In [60]: res=lbl[ind] In [61]: res Out[61]: array(['A', 'E', 'F', 'C'], dtype=object) 确定是使用了该映射值还是某些where。使用None dtype可以轻松地用其他内容替换字符串标签,objectNone等。

no_region

答案 1 :(得分:0)

这些方面的某些内容应该有效地完成,但现在无法进行测试:

rows = len(prediction)
p = prediction[np.arange(rows), catIndex.flatten()]
catResult = np.empty(rows, 'S1').fill('n')
catResult[p] = categories[catIndex.flatten()][p]
相关问题