기능이 여러 조건 인 Numpy
dists라는 거리 배열이 있습니다. 두 값 사이의 dists를 선택하고 싶습니다. 이를 위해 다음 코드 줄을 작성했습니다.
dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]
그러나 이것은 조건에 대해서만 선택합니다
(np.where(dists <= r + dr))
임시 변수를 사용하여 순차적으로 명령을 수행하면 정상적으로 작동합니다. 위의 코드가 작동하지 않는 이유는 무엇이며 어떻게 작동합니까?
건배
특정 경우 에 가장 좋은 방법은 두 가지 기준을 하나의 기준으로 변경하는 것입니다.
dists[abs(dists - r - dr/2.) <= dr/2.]
그것은 하나 개의 부울 배열을 생성하고, 내 의견으로는, 그것이 말하는 때문에 쉽게 읽을 수 있다 dist
내에서 dr
또는 r
? (하지만 r
처음부터 관심 지역의 중심으로 재정의하고 싶지만 r = r + dr/2.
) 그러나 귀하의 질문에 대답하지 않습니다.
귀하의 질문에 대한 답변 : 기준에 맞지 않는 요소를 필터링하려고하는 경우
실제로 필요 하지 않습니다.where
dists
dists[(dists >= r) & (dists <= r+dr)]
&
는 요소별로 요소를 제공 하기 때문에 and
(괄호가 필요합니다).
또는 where
어떤 이유로 사용하려면 다음을 수행하십시오.
dists[(np.where((dists >= r) & (dists <= r + dr)))]
이유 :
작동하지 않는 이유 np.where
는 부울 배열이 아닌 인덱스 목록을 반환 하기 때문 입니다. and
두 숫자 목록 사이 를 가져 오려고하는데 물론 True
/ False
값 이 없습니다 . 경우 a
와 b
모두 True
값, 다음 a and b
반환 b
. 따라서 이와 같은 말 [0,1,2] and [2,3,4]
은 당신에게 줄 것 [2,3,4]
입니다. 여기 실제로 작동합니다.
In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1
In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)
In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
예를 들어 비교하려고 한 것은 단순히 부울 배열이었습니다.
In [236]: dists >= r
Out[236]:
array([False, False, False, False, False, False, False, False, False,
False, True, True, True, True, True, True, True, True,
True, True], dtype=bool)
In [237]: dists <= r + dr
Out[237]:
array([ True, True, True, True, True, True, True, True, True,
True, True, True, True, False, False, False, False, False,
False, False], dtype=bool)
In [238]: (dists >= r) & (dists <= r + dr)
Out[238]:
array([False, False, False, False, False, False, False, False, False,
False, True, True, True, False, False, False, False, False,
False, False], dtype=bool)
이제 np.where
결합 된 부울 배열을 호출 할 수 있습니다 .
In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)
In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. , 5.5, 6. ])
또는 멋진 색인 생성을 사용하여 원래 배열을 부울 배열로 색인화합니다.
In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. , 5.5, 6. ])
수락 된 답변이 문제를 잘 설명했기 때문에. 여러 조건에 더 적합한 numpy 논리 함수 를 사용할 수도 있습니다 .
np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))
나는 np.vectorize
그러한 작업 에 사용 하고 싶습니다 . 다음을 고려하세요:
>>> # function which returns True when constraints are satisfied.
>>> func = lambda d: d >= r and d<= (r+dr)
>>>
>>> # Apply constraints element-wise to the dists array.
>>> result = np.vectorize(func)(dists)
>>>
>>> result = np.where(result) # Get output.
선명한 출력 np.argwhere
대신에 사용할 수도 있습니다 np.where
. 그러나 그것은 당신의 전화입니다 :)
도움이 되길 바랍니다.
시험:
np.intersect1d(np.where(dists >= r)[0],np.where(dists <= r + dr)[0])
이것은 작동해야합니다 :
dists[((dists >= r) & (dists <= r+dr))]
가장 우아한 방법 ~~
시험:
import numpy as np
dist = np.array([1,2,3,4,5])
r = 2
dr = 3
np.where(np.logical_and(dist> r, dist<=r+dr))
출력 : (배열 ([2, 3]),)
자세한 내용 은 논리 기능 을 참조하십시오.
이 간단한 예제를 해결했습니다.
import numpy as np
ar = np.array([3,4,5,14,2,4,3,7])
print [X for X in list(ar) if (X >= 3 and X <= 6)]
>>>
[3, 4, 5, 4, 3]
One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.
When we use 'and':
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)
Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
When we use Ampersand(&):
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)
Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')
And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.
참고URL : https://stackoverflow.com/questions/16343752/numpy-where-function-multiple-conditions
'program tip' 카테고리의 다른 글
NSURL을 로컬 파일 경로로 변환 (0) | 2020.08.05 |
---|---|
C #에서 유형을 매개 변수로 전달 (0) | 2020.08.05 |
넷빈즈 : @author를 변경하는 방법 (0) | 2020.08.05 |
ASP.NET 2.0-app_offline.htm 사용 방법 (0) | 2020.08.05 |
Android : HTTP 통신은 "Accept-Encoding : gzip"을 사용해야합니다. (0) | 2020.08.05 |