沿numpy数组中的最后一个轴匹配 [英] Match along last axis in numpy array

查看:183
本文介绍了沿numpy数组中的最后一个轴匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了很多有关在python中切片3D列表的文章和其他问题的答案,但是我无法将这些方法应用于我的情况.

I saw a lot of articles and answers to other questions about slicing 3D lists in python, but I can't apply those methods to my case.

我有一个3D列表:

list = [
    [[0, 56, 78], [4, 86, 90], [7, 87, 34]],
    [[1, 49, 76], [0, 76, 78], [8, 60, 7]], 
    [[9, 6, 58], [6, 57, 78], [10, 46, 2]]
    ]

第3维的最后2个值保持不变,但是每次我重新运行代码时都会更改.代码需要做的是找到最后2个值中的2对特定的对,并从一对对切成薄片.例如:

The the last 2 values of the 3rd dimension stay constant but change every time I rerun the code. What the code needs to do is find 2 specific pairs of those last 2 values and slice from one pair to the other. So for example:

pair1 = 86, 90
pair2 = 76, 78

输出应为:

[4, 86, 90], [7, 87, 34], [1, 49, 76], [0, 76, 78]

我知道如何找到2对,但我不确定如何对列表进行切片.预先感谢您的帮助,如果有不清楚的地方,请发表评论.

I know how to find the 2 pairs, I'm just not sure how to slice the list. Thanks in advance for your help and leave a comment if something is unclear.

推荐答案

使用numpy,您可以对数组进行切片以将最后两个元素保留在最后一个轴上,找到每对发生的索引,将结果展平并使用将其切成数组:

Using numpy, you can slice the array to keep the last two elements on the last axis, find the indices where each pair takes place, flatten the result and use it to slice the array:

a = np.array(my_list) # don't call your list "list"

a_sliced = a[...,1:]

ix1 = np.flatnonzero((a_sliced  == pair1).all(-1).ravel()).item()

ix2 = np.flatnonzero((a_sliced  == pair2).all(-1).ravel()).item()

np.concatenate(a)[ix1:ix2+1]

array([[ 4, 86, 90],
       [ 7, 87, 34],
       [ 1, 49, 76],
       [ 0, 76, 78]])


a被定义为一个numpy数组,两对都定义为元组:


a being defined as a numpy array, and both pairs defined as tuples:

pair1 = 86, 90
pair2 = 76, 78

这篇关于沿numpy数组中的最后一个轴匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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