首页 > 解决方案 > numpy 数组索引技术如何为相同的输入代码提供不同的输出?

问题描述

#Code

import numpy as np    
np.random.seed(124)
x_2d = np.random.randint(1,50,(3,4,5))
print("I am getting wrong output => {}".format(x_2d[0][:][1]))
print("This is what I want => {} ".format(x_2d[0,:,1]))

# Code Ended

# Output for above code

I am getting wrong output => [42  1 21 29 15]
This is what I want => [29  1 22 49] 

我是 NumPy 的新手,所以我只是在尝试 numpy 数组选择技术。我知道我们可以使用方括号法或逗号法。但是我遇到了一个问题。我正在尝试提取数组 0 的列索引 1。但是当我使用这两种技术时,我得到了不同的输出。我附上了代码片段和输出。谁能指导我哪里出错了?

标签: pythonpandasnumpyrandomarray-indexing

解决方案


x[0][:][1]等价于x[0, 1, :],也等价于x[0][1]

孤独的原因[:]基本上意味着“复制这个数组”,无论是在基本的 Python 还是 Numpy 中。所以你可以读x[0][:][1]作“取数组 x 的第一个元素,复制它,然后取结果的第二个元素。”

[:]并不意味着“跳过一个维度”。


推荐阅读