如何用另一个ndarray索引一个ndarray? [英] How to index a ndarray with another ndarray?

查看:103
本文介绍了如何用另一个ndarray索引一个ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用python/numpy做一些机器学习的东西,我想用一维ndarray索引一个二维ndarray,以便获得带有索引值的一维数组.

I am doing some machine learning stuff in python/numpy in which I want to index a 2-dimensional ndarray with a 1-D ndarray, so that I get a 1-D array with the indexed values.

我了解到它可以处理一些丑陋的代码,并且我想知道是否有更好的方法,因为对于像python + numpy这样的好语言和模块组合来说,这似乎是不自然的.

I got it to work with some ugly piece of code and I would like to know if there is a better way, because this just seems unnatural for such a nice language and module combination as python+numpy.

   a = np.arange(50).reshape(10, 5) # Array to be indexed
   b = np.arange(9, -1, -2) # Indexing array
   print(a)
   print(b)
   print(a[b, np.arange(0, a.shape[1]).reshape(1,a.shape[1])])
   #Prints:
   [[ 0  1  2  3  4]
    [ 5  6  7  8  9]
    [10 11 12 13 14]
    [15 16 17 18 19]
    [20 21 22 23 24]
    [25 26 27 28 29]
    [30 31 32 33 34]
    [35 36 37 38 39]
    [40 41 42 43 44]
    [45 46 47 48 49]]

   [9 7 5 3 1]

   [[45 36 27 18  9]]

这正是我想要的(即使从技术上讲是二维ndarray),但这似乎非常复杂.有没有更整洁的方式?

This is exactly what I want(even though technically a 2-D ndarray), but this seems very complicated. Is there a neater and tidier way?

为了澄清,我实际上不想要一维数组,这很难解释.实际上,我确实想要一个长度为1的维度,因为这是以后处理它所需要的,但这可以通过reshape()语句轻松实现.抱歉,我只是将我的实际代码与更笼统的问题混在一起了.

To clarify, I actually I do not want a 1-D array, that was very poorly explained. I actually do want one dimension with length 1, because that is what I need for processing it later, but this would be easily achieved with a reshape() statement. Sorry for the confusion, I just mixed my actual code with the more general question.

推荐答案

您想要一个1D数组,但是您包含了一个reshape调用,其唯一目的是将数组从所需格式转换为您不想使用的格式.不想.

You want a 1D array, yet you included a reshape call whose only purpose is to take the array from the format you want to a format you don't want.

停止重塑arange输出.另外,您无需明确指定0起始值:

Stop reshaping the arange output. Also, you don't need to specify the 0 start value explicitly:

result = a[b, np.arange(a.shape[1])]

这篇关于如何用另一个ndarray索引一个ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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