Python 沿轴的最大值(单位:numpy)
假设我有一个numpy数组,如下所示:Python 沿轴的最大值(单位:numpy),python,numpy,Python,Numpy,假设我有一个numpy数组,如下所示: >custom_array=np.array([[0.1,0.4,0.4], [0.3, 0.2, 0.7]], [[0.9, 0.4, 0.2], [0.5, 0.1, 0.1]]]) >>自定义数组.shape (2,2,3) 上面的数组表示概率表: | X1 | X2 | X3 | P | |---- |---- |---- |----- | | 0 | 0 | 0 | 0.1 |
>custom_array=np.array([[0.1,0.4,0.4],
[0.3, 0.2, 0.7]],
[[0.9, 0.4, 0.2],
[0.5, 0.1, 0.1]]])
>>自定义数组.shape
(2,2,3)
上面的数组表示概率表:
| X1 | X2 | X3 | P |
|---- |---- |---- |----- |
| 0 | 0 | 0 | 0.1 |
| 0 | 0 | 1 | 0.4 |
| 0 | 0 | 2 | 0.4 |
| 0 | 1 | 0 | 0.3 |
| 0 | 1 | 1 | 0.2 |
| 0 | 1 | 2 | 0.7 |
| 1 | 0 | 0 | 0.9 |
| 1 | 0 | 1 | 0.4 |
| 1 | 0 | 2 | 0.2 |
| 1 | 1 | 0 | 0.5 |
| 1 | 1 | 1 | 0.1 |
| 1 | 1 | 2 | 0.1 |
我想获得沿轴0和轴2的指数,这些指数使沿轴=1(第二个轴)的值最大化。我的预期输出应该是:
(1,0)=>因为当X2=0时,X1和X3的组合使p的值最大化
(0,2)=>因为当X2=1时,X1和X3的组合使p的值最大化
我尝试了以下命令:
np.unravel\u索引(custom\u array.argmax(),custom\u array.shape)
(1,0,0)
这是正确的答案,但我不知道如何修改此命令以提供上述两种输出
如果社区能提供任何提示,我将不胜感激。谢谢 要获取(例如打印)最大元素的索引,请使用以下命令
代码:
详情:
-迭代X2的值对于i in…
-源数组中特定值为X2的片段tbl
-扁平数组中最大元素的索引np.argmax(tbl)
-转换为基础数组(tbl)中的索引np.展开索引
0: (1, 0)
1: (0, 2)
要查找X2为0的切片中的索引,请使用:
from numpy import array, where
array(where(custom_array[:, 0, :] == custom_array[:, 0, :].max())).squeeze()
要查找X2为1的切片中的索引,请使用:
array(where(custom_array[:, 1, :] == custom_array[:, 1, :].max())).squeeze()
要查找具有任意数量X2值的数组,请使用:
[array(where(custom_array[:, i, :] == custom_array[:, i, :].max())).squeeze()
for i in range(custom_array.shape[1])]
[array(where(custom_array[:, i, :] == custom_array[:, i, :].max())).squeeze()
for i in range(custom_array.shape[1])]