2016-03-26 4 views
2

私はfollを持っています。 Pythonのnumpyの配列、編曲:どのように私は0または3.pythonの特定の値の前の最後の要素の位置を見つけるnumpy

前の最後の1の位置を見つけるのですか

np.where(arr.squeeze() == 1)[0] 

([1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 3L, 3L, 3L, 2L, 2L, 2L, 
     2L, 2L, 2L, 1L, 1L, 1L, 1L]) 

私はこのような1の最初の発生を見つけることができます

答えて

1

はここnp.wherenp.in1d使用して一つのアプローチだ -

# Get the indices of places with 0s or 3s and this 
# decides the last index where we need to look for 1s later on 
last_idx = np.where(np.in1d(arr,[0,3]))[0][-1] 

# Get all indices of 1s within the range of last_idx and choose the last one 
out = np.where(arr[:last_idx]==1)[0][-1] 

にはインデックスが見つからない場合のために、[0][-1]のようなものを使用しても何の要素を持っていない文句を言うだろうことに注意してください、そうエラーチェックコードがあることを必要としていますこれらの行に囲まれています。

サンプル実行 -

In [118]: arr 
Out[118]: array([1, 1, 3, 0, 3, 2, 0, 1, 2, 1, 0, 2, 2, 3, 2]) 

In [119]: last_idx = np.where(np.in1d(arr,[0,3]))[0][-1] 

In [120]: np.where(arr[:last_idx]==1)[0][-1] 
Out[120]: 9 
1

あなたはrolling windowを使用して、必要な値のためにそれを検索することができます。

import numpy as np 
arr = np.array([1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 3L, 3L, 3L, 2L, 2L, 2L, 
     2L, 2L, 2L, 1L, 1L, 1L, 1L]) 

def rolling_window(a, window): 
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) 
    strides = a.strides + (a.strides[-1],) 
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) 

match_1_0 = np.all(rolling_window(arr, 2) == [1, 0], axis=1) 
match_1_3 = np.all(rolling_window(arr, 2) == [1, 3], axis=1) 
all_matches = np.logical_or(match_1_0, match_1_3) 
print(np.flatnonzero(all_matches)[-1]) 

Dependiあなたの配列に、これは十分にパフォーマンスが良いかもしれません。ことで、あまり柔軟性(しかし、単純な)ソリューション ...より良い、それはあなたが通常がnumpyのを避けたいのインデックスを超えるループであっても実行することがあります:

for ix in xrange(len(arr) - 2, -1, -1): # range in python3.x 
    if arr[ix] == 1 and (arr[ix + 1] == 0 or arr[ix + 1] == 3): 
     return ix 

あなたもあるかもしれませんどのように、おそらく上記のハードコード化されたソリューションよりも少し柔軟性があり、おそらくまだ出て、実行することになり、ローリングウィンドウ溶液(私が推測する)何かを行うことができる:ここで

def rfind(haystack, needle): 
    len_needle = len(needle) 
    for ix in xrange(len(haystack) - len_needle, -1, -1): # range in python3.x 
     if (haystack[ix:ix + len_needle] == needle).all(): 
      return ix 

を、あなたが何かをしたいですlike:

max(rfind(arr, np.array([1, 0])), rfind(arr, np.array([1, 3]))) 

もちろん、これらすべての回答では、実際にあなたが探しているものが存在しないケースは処理していません

関連する問題