Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 沿轴的最大值(单位:numpy)_Python_Numpy - Fatal编程技术网

Python 沿轴的最大值(单位: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 |

假设我有一个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   |
| 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) 这是正确的答案,但我不知道如何修改此命令以提供上述两种输出

如果社区能提供任何提示,我将不胜感激。谢谢

要获取(例如打印)最大元素的索引,请使用以下命令 代码:

详情:

  • 对于i in…
    -迭代X2的值
  • tbl
    -源数组中特定值为X2的片段
  • np.argmax(tbl)
    -扁平数组中最大元素的索引
  • np.展开索引
    -转换为基础数组(tbl)中的索引
对于您的数据样本,结果是:

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])]