Python中如何通过索引矩阵从NumPy向量和矩阵选取值?
按索引提取NumPy元素的实现
先给出我们的原始数据:
import numpy as np v = np.array([10, 15, 20, 25]) m = np.array([[0.1, 0.2, 0.3, 0.4], [0.1, 0.5, 0.3, 0.4], [0.12, 0.8, 0.1, 0.2], [0.7, 0.0, 0.2, 0.4]]) m_index = np.array([[1, 2], [3, 0], [1, 2], [0, 2]])
任务1:从向量v中按索引提取元素
直接利用NumPy的索引广播特性,将m_index作为索引传入v即可得到目标矩阵:
result_v = v[m_index] print(result_v)
输出结果:
[[15 20] [25 10] [15 20] [10 20]]
任务2:从矩阵m的对应行中按索引提取元素
需要为每一行匹配对应的行索引,结合m_index中的列索引来提取元素。通过np.arange生成行索引数组并变形为列向量,再与m_index配合完成索引:
row_indices = np.arange(m.shape[0])[:, None] result_m = m[row_indices, m_index] print(result_m)
输出结果:
[[0.2 0.3] [0.4 0.1] [0.8 0.1] [0.7 0.2]]
内容的提问来源于stack exchange,提问作者Fredrik
相关产品推荐
相关产品推荐

