如何从Python / numpy中的nd-array中的每一行中选择不同的列? [英] How to select different columns from each row in nd-array in Python/numpy?

查看:909
本文介绍了如何从Python / numpy中的nd-array中的每一行中选择不同的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有3 x 2矩阵

Suppose I have 3 x 2 matrix

A = np.arange(3*2).reshape(3,2)

并希望按索引数组选择元素

and wish to select elements by index array

I = [0, 1, 0]

得到

[[0],[3],[4]]

我该怎么做?

这样写

A[:,[0,1,0]]

给出了完全不同的东西(什么?)

gives something completely different (what?)

推荐答案

你可以做的是传递第一维值的可迭代,以及第二维的可迭代(例如列表)。类似于:

What you can do is pass an iterable of the first dimesion value, and an iterable (e.g. a list) of the second dimension. Something like:

I = [0, 1, 0]
A[range(len(I)),I]

这会产生:

>>> A[range(len(I)),I]
array([0, 3, 4])

如果您想要它作为二维数组,您可以使用额外的重塑:

In case you want it as a 2d array, you can use an additional reshape:

>>> A[range(len(I)),I].reshape(-1,1)
array([[0],
       [3],
       [4]])




A[:,[0,1,0]]

给出完全不同的东西(什么?)

gives something completely different (what?)

它创建一个矩阵,其中第一个列是第一个( 0 )列 A second 列是<$ c的第二列( 1 ) $ c> A ,第三列又是 A 0 ) c>。

It creates a matrix where the first column is the first (0) column of A, the second column is the second (1) column of A, and the third column is again the first (0) column of A.

这篇关于如何从Python / numpy中的nd-array中的每一行中选择不同的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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