python,如何从矩阵的每一列中选择元素 [英] python, how to select element from each column of matrix

查看:85
本文介绍了python,如何从矩阵的每一列中选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据索引向量从矩阵的每一列中提取一个元素。说:

I need to extract one element from each column of a matrix according to an index vector. Say:

index = [0,1,1]
matrix = [[1,4,7],[2,5,8],[3,6,9]]

索引向量告诉我需要列1中的第一个元素,列2中的第二个元素,列3中的第三个元素。

Index vector tells me I need the first element from column 1, second element from column 2, and third element from column 3.

输出应为 [1,5 ,8]

谢谢

推荐答案

您可以使用高级索引

index = np.array([0,1,2])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])

res = matrix[np.arange(matrix.shape[0]), index]
# array([1, 5, 9])

第二次例如,反转索引:

For your second example, reverse your indices:

index = np.array([0,1,1])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])

res = matrix[index, np.arange(matrix.shape[1])]
# array([1, 5, 8])

这篇关于python,如何从矩阵的每一列中选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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