python - 如何使用 numpy 更优雅地实现这个 for 循环?
问题描述
这是我的代码片段。有人可以采取适当的方式来做到这一点。一些花哨的 NumPy 技巧?
q_val = np.random.rand(5,3)
action = np.ones((5,1),int)
to_set = np.ones((5,1),int)
for x in range(5):
q_val[x][action[x]] -= to_set[x]
这就是我实例化值的方式
q_val = np.random.rand(5,3) //lets say the middel of randome
q_val = array([[0.93373647, 0. , 0.14962181],//get only zeroes
[0.67909199, 0. , 0.07462584],
[0.05696713, 0. , 0.03221326],
[0.78209394, 0. , 0.58312439],
[0.09217555, 0. , 0.17876316]])
action = np.ones((5,1),int)
action = >>> action
array([[1],
[1],
[1],
[1],
[1]])
to_set = np.ones((5,1),int)
to_set = array([[1],
[1],
[1],
[1],
[1]])
这就是我要改变的
for x in range(5):
q_val[x][action[x]] -= to_set[x]
这就是我会得到的
array([[ 0.93373647, -1. , 0.14962181],
[ 0.67909199, -1. , 0.07462584],
[ 0.05696713, -1. , 0.03221326],
[ 0.78209394, -1. , 0.58312439],
[ 0.09217555, -1. , 0.17876316]])
我确信有一些奇特的方法可以在其中一条线上做到这一点。有人可以帮忙吗?
解决方案
您可以只使用数组来索引其他数组:
index = np.arange(len(action))
q_val[index, action] -= to_set[index]
推荐阅读
- angular - 如何在打字稿中插入&&签入开关表达式
- html - Flickity CSS 样式未应用
- ms-word - Microsoft Word 文档无法打开并出现错误:Word 发现无法读取的内容
- python - 分发或安装 C++ Python 扩展 Pyd 文件
- html - 带有 TailwindCSS 内存泄漏的 HTML
- c# - 您能否使用 Rider 向 C# 项目添加新的设置文件,并自动生成 Designer 文件?
- mongodb - 如何在猫鼬中使用“LIKE”运算符来获取特定数据
- ios - 在 config.xml 中设置使用说明后,Ionic IOS 相机权限仍然被拒绝
- php - 使用 PHP 创建具有相同键的关联数组的数组
- python - Python - 在新文件中添加 2 个文件的 JSON 数据