여기 특정 간격 멈추고 단순히 우리가 원하는 출력을 제공 할 b
로 인덱싱 따른다 단차 인덱스를 만드는 np.maximum.accumulate
및 np.where
의 조합을 이용하는 방법이다.
따라서, 구현 될 것이다 -
mask = a!="b"
idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
out = b[idx]
샘플 단계별 실행 -
가
In [656]: # Inputs
...: a = np.array(['a', 'b', 'a', 'a', 'b', 'a'])
...: b = np.array([150, 154, 147, 126, 148, 125])
...:
In [657]: mask = a!="b"
In [658]: mask
Out[658]: array([ True, False, True, True, False, True], dtype=bool)
# Crux of the implmentation happens here :
In [696]: np.where(mask,np.arange(mask.size),0)
Out[696]: array([0, 0, 2, 3, 0, 5])
In [697]: np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
Out[697]: array([0, 0, 2, 3, 3, 5])# Stepped indices "intervaled" at masked places
In [698]: idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
In [699]: b[idx]
Out[699]: array([150, 150, 147, 126, 126, 125])
간단하고 간결한 솔루션입니다. 그러나 왜 그것이 [150 0 147 126 0 125]를 반환합니까? a [i] = "b"인 경우 'b'배열에서 값을 가져 오지 않습니다. –
질문을 잘못 읽었습니다. 이것은 이미'c'의 모든 요소를 가지고 있지만 루프를 통해 채워 넣을 때만 작동합니다. 그래서 약간 더 복잡해집니다. – pbreach