python - 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。但是当我使用这两种技术时,我得到了不同的输出。我附上了代码片段和输出。谁能指导我哪里出错了?
解决方案
x[0][:][1]
等价于x[0, 1, :]
,也等价于x[0][1]
。
孤独的原因[:]
基本上意味着“复制这个数组”,无论是在基本的 Python 还是 Numpy 中。所以你可以读x[0][:][1]
作“取数组 x 的第一个元素,复制它,然后取结果的第二个元素。”
[:]
并不意味着“跳过一个维度”。
推荐阅读
- magento - Magento 2.3.4 在我的本地主机中无法正常工作
- bash - 将多个函数传递给远程 shell/mkdir 找不到目录
- gradle - Gradle can't find dependency in private nexus repo
- git - GitHub 贡献页面显示太多更改
- port - How to chain port calls?
- python - 更改特定 ytick matplotlib 的颜色
- sql - Oracle 数据库架构
- python-3.x - 从 espn statsguru 抓取数据
- java - Limiting the length of a toString return
- python - pyqtgraph: problem setting smooth=False on a GLSurfacePlotItem object