给定行和列索引,分配到NumPy数组的网格中 [英] Assign into a grid of a NumPy array given row and column indices

查看:57
本文介绍了给定行和列索引,分配到NumPy数组的网格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问2d numpy数组的特定行和列限制.

I want to access a specific row and column restriction of a 2d numpy array.

> x
array([[1, 2, 0],
       [3, 4, 0],
       [0, 0, 1]])

如果我做自然的事情,我只会得到受限数组的对角线元素.

If I do what seems natural, I just get the diagonal elements of the restricted array.

> x[[0,1], [0,1]]
array([1, 4])

相反,我可以这样做来阅读我想要的内容-

Instead I can do this to read what I want -

> x[[0,1],:][:,[0,1]]
array([[1, 2],
       [3, 4]])

..但是它不允许我编写/分配值.

..but it doesn't let me write/assign the values.

> x[[0,1],:][:,[0,1]] = np.array([[1,0],[0,1]])

> x 
array([[1, 2, 0],
       [3, 4, 0],
       [0, 0, 1]])

如何在此处写入矩阵?

推荐答案

使用

Use np.ix_ to map that grid of elements and then assign -

x[np.ix_([0,1], [0,1])] = np.array([[1,0],[0,1]])

这篇关于给定行和列索引,分配到NumPy数组的网格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆