numpy堆栈到二维数组,从另一个堆栈中按索引选择

时间:2018-08-22 13:21:30

标签: python arrays numpy indexing

我有两组分类(Lc1Lc2)和两组概率(Lp1Lp2)。 Lp1是描述Lc1中分类可能性的几组概率。我想使用Lc1中最有可能的分类来合并Lc2class_result中的信息。

import numpy as np

#example data
Lp1 = np.ones((2,2))*0.5
Lc2 = np.ones((2,2))

Lc1 = np.ones((2,2))
Lp2 = np.ones((2,2))*0.5

#Change some values for the example
Lp1[1,1] =0.95
Lc1[1,1] = 0

Lc2[0,1]=3
Lp2[0,1]=.95

p_stack = np.stack((Lp1,Lp2))
c_stack = np.stack((Lc1,Lc2))

index = np.argmax(p_stack, axis=2)

class_result = np.take(c_stack, index)

我的初始方法是为一组分类和概率创建一个np.stack,并使用np.argmax查找在p_stack中出现最大值的轴索引。 np.take的文档似乎描述了我需要执行的操作,但是我不明白为什么它返回带有1的数组。是否可以通过指定我要选择的值的轴来减少np.stack的维数?

我想要的结果是:

class_result = np.array([[1,3],[1,0]])

1 个答案:

答案 0 :(得分:0)

In your case ìndex refers to the first dimension, and you need to create ascending indices for the other dimensions.

If you write them manually it looks like

dim_1 = np.array([[0, 0],
                  [1, 1]])


dim_2 = np.array([[0, 1],
                  [0, 1]])

print(c_stack[index, dim_1, dim_2])

You can create them automatically using np.arange, np.vstack, np.hstack and np.tile, np.column_stack. There are several ways to do this.

E.g.

x = np.arange(5)

a = np.tile(x, (5, 1))
b = np.column_stack(tuple(a))
print(a)
print(b)

This technique in Numpy is called "Integer array indexing".