python - 切片 3D 数组 numpy
问题描述
考虑以下:
In[1]: pos
Out[1]:
array([[0, 1, 2, 3],
[2, 3, 4, 5],
[0, 1, 6, 7],
[2, 3, 6, 7],
[2, 3, 8, 9],
[4, 5, 8, 9],
[6, 7, 8, 9]])
In[2]: pos = pos.reshape((7,1,4))
Out[2]:
array([[[0, 1, 2, 3]],
[[2, 3, 4, 5]],
[[0, 1, 6, 7]],
[[2, 3, 6, 7]],
[[2, 3, 8, 9]],
[[4, 5, 8, 9]],
[[6, 7, 8, 9]]])
In[3]: af = np.zeros((7,10,4))
我想根据下面的循环在特定位置替换 af 数组:
for i in range(7):
af[i,pos[i],pos[0]] = 1
有了这个,我想知道是否有任何方法可以在没有循环的情况下进行这种替换。
解决方案
In [391]: pos = np.array([[0, 1, 2, 3],
...: [2, 3, 4, 5],
...: [0, 1, 6, 7],
...: [2, 3, 6, 7],
...: [2, 3, 8, 9],
...: [4, 5, 8, 9],
...: [6, 7, 8, 9]])
In [392]: af = np.zeros((7,10,4),int)
In [393]: for i in range(7):
...: af[i,pos[i],pos[0]] = 1
...:
pos
重塑有什么不同吗?
In [395]: pos1 = pos.reshape((7,1,4))
In [398]: af1 = np.zeros((7,10,4),int)
In [399]: for i in range(7):
...: af1[i,pos1[i],pos1[0]] = 1
...:
...:
In [400]: np.allclose(af,af1)
Out[400]: True
不,所以让我们忘记它。
正如我所评论x[np.arange(n), idx]
的,这是一种分配值的常用方法,例如您的循环。索引数组需要相互广播以定义所需的元素。
如果我们尝试:
In [403]: af[np.arange(7),pos,pos[0]]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-403-6488d02c6898> in <module>
----> 1 af[np.arange(7),pos,pos[0]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (7,) (7,4) (4,)
因此,让我们制作第一个索引 (7,1) 形状:
In [404]: af[np.arange(7)[:,None],pos,pos[0]]
Out[404]:
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
In [405]: af2 = np.zeros((7,10,4),int)
In [406]: af2[np.arange(7)[:,None], pos,pos[0]] = 1
In [407]: np.allclose(af,af2)
Out[407]: True
推荐阅读
- apache - 将mod_perl加载到xampp时如何调试“找不到符号”?
- android - 如何允许用户从 Android 应用程序登录 AWS 控制台
- android - 如何从适配器获取复选框值到片段
- python - 如何使用 python 正确查询 MongoDB 嵌套文档?
- svg - 过滤器的处理顺序是什么
- javascript - 定义一个 JavaScript 对象两个单独的变量
- html - 不扩展 Flex Grow
- python - 如何删除文件中不同样式的行(一切都是str格式)?
- video - 如何使用ffmpeg对多路视频进行编码?
- html - 我可以使用 POST 方法在表单中输入 GET 参数吗