python - 从列表索引为 numpy 数组赋值
问题描述
我有一个 numpy 数组和一个列表,比如:
np_array = np.random.randint(0,3,(2,3))
np_array
array([[1, 1, 2],
[2, 1, 2]])
indices_list:
[7,8,9]
并希望有一个 numpy 数组,它从列表的索引中获取其值(即,如果 np_array 的值为 2,则将 indices_list[2] 设置为新数组的值):
np_array_expected
array([[8, 8, 9],
[9, 8, 9]])
我做了这个不成功的尝试:
np_array[indices_list]
Traceback (most recent call last):
File "/tmp/ipykernel_27887/728354097.py", line 1, in <module>
np_array[indices_list]
IndexError: index 7 is out of bounds for axis 0 with size 2
indices_list[np_array]
Traceback (most recent call last):
File "/tmp/ipykernel_27887/265649000.py", line 1, in <module>
indices_list[np_array]
TypeError: only integer scalar arrays can be converted to a scalar index
解决方案
这只是索引: b[a]
,因为第二个数组也是 numpy 数组。
输出:
array([[8, 8, 9],
[9, 8, 9]])
推荐阅读
- java - 图形/JPanel 尺寸不是以像素为单位测量的吗?
- c - 为什么第 10 个循环在 C 程序中结束时循环语句会出错?
- swiftui - 如何在 SwiftUI 中手动显示 contextMenu?
- python - 字符串识别前阈值不正确
- android - 如何在 PreferenceScreen 中显示 RadioButton 列表(不在对话框中)
- spring - 仅更新现有实体的“更改值”
- javascript - React Native Flatlist 在上拉时不刷新数据
- django - 错误 5 IIS 上的访问被拒绝 (python.exe)
- azure - 创建时间后如何获取 Azure 服务主体的密码?
- c# - 将带有 GROUP BY 和 COUNT 的查询转换为 Linq