切片和更改numpy 2D数组,每行的列索引列表不同 [英] Slice and change numpy 2D array with list of column indices different for each row

查看:162
本文介绍了切片和更改numpy 2D数组,每行的列索引列表不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用列索引列表对2D numpy数组进行切片.困难之处在于每一行的列索引都不同.例如:

I would like to slice a 2D numpy array using a list of column indices. The difficulty is the column indices are different for each row. For example:

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

并且我有一个列索引列表

and I have a list of column indices as

indices = [[0, 1], [2, 1], [2, 2]]

这意味着我想获得第0行的列[0,1],第1行的列[2, 1]和第2行的列[2, 2].结果应该是

which means I would like to get column [0,1]for row 0, column [2, 1] for row 1, and column [2, 2] for row 2. The result should be

result = np.array([0, 1],
                  [5, 4],
                  [8, 8]])

如何在不涉及for循环的情况下使用numpy的切片?

How do I use numpy's slicing without involving a for loop?

我看到了一些使用np.take_along_axis(x, indices, 1)提及的答案.此函数通过处理原始数组中的值来创建一个新数组.这非常适合从数组中读取值,但不能用于增加原始数组的值.是否有任何类似的矩阵可用于修改原始数组的值,例如np.take_along_axis(x, indices, 1) += 10?当然,行的列索引是唯一的以避免歧义.

I saw some answers mentioning using np.take_along_axis(x, indices, 1) This function creates a new array by coping the value from the original array. This is great for reading value from an array, but cannot be used to increment the value of the original array. Is there any similar matrices that can be used for modifying the value of the original array, e.g. np.take_along_axis(x, indices, 1) += 10? Of course the column indices for a row are unique to avoid ambiguity.

推荐答案

您要 numpy.take_along_axis

np.take_along_axis(x, np.array(indices), axis = 1)
Out[]: 
array([[0, 1],
       [5, 4],
       [8, 8]])

这篇关于切片和更改numpy 2D数组,每行的列索引列表不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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