2010-02-21 3 views
1

현재 배열의 주어진 요소가 같음 = 0인지 확인한 다음 값을 'level'값으로 설정하면 (temp_board는 2D numpy 배열이고 indices_to_watch는 감시되어야하는 2D 좌표를 포함합니다 0).Numpy 가면 배열 수정

indices_to_watch = [(0,1), (1,2)] 
    for index in indices_to_watch: 
     if temp_board[index] == 0: 
      temp_board[index] = level 

나는 더 NumPy와 같은 접근 방식이 변환 (의 제거 만 NumPy와 기능을 사용)이 속도를 싶습니다. 0이있는 콘크리트를 배열 요소를 업데이트하는 다른 방법이,

masked = np.ma.array(temp_board, mask=(a!=0), hard_mask=True) 
    masked.put(indices_to_watch, level) 

그러나 (완전히 이상한!) 1D 크기를 가지고 싶어() 넣어 할 때 불행하게도 배열을 마스크 : 는 여기에 내가 뭘하려입니다 지수?

가면 배열을 사용하는 것이 최선의 방법이 아닙니까?

답변

1

당신이 당신이 이런 식으로 원하는 할 수있는, temp_board0 어디에 있는지 찾기가 매우 비효율적이라고 가정 : 위의 작업을 수행 할 수없는 경우

# First figure out where the array is zero 
zindex = numpy.where(temp_board == 0) 
# Make a set of tuples out of it 
zindex = set(zip(*zindex)) 
# Make a set of tuples from indices_to_watch too 
indices_to_watch = set([(0,1), (1,2)]) 
# Find the intersection. These are the indices that need to be set 
indices_to_set = indices_to_watch & zindex 
# Set the value 
temp_board[zip(*indices_to_set)] = level 

, 그럼 여기 있어요 방법,하지만 난 그게 가장 파이썬 있는지 확실하지 않다하십시오 NumPy와 배열로 변환

indices_to_watch = [(0,1), (1,2)] 

첫째 :

설정이어서

indices_to_set = numpy.where(temp_board[index] == 0) 

, 실제 인덱스를 알아낼 :이어서,

index = zip(*indices_to_watch) 

를 조건을 검사 : 516,

indices_to_watch = numpy.array(indices_to_watch) 

그리고,이 인덱싱 할

final_index = zip(*indices_to_watch[indices_to_set]) 

를 마지막 값을 설정하십시오 :

temp_board[final_index] = level 
+0

고맙습니다. numpy.where를 시도했지만 설정 교차로와 결합하지 않았습니다. –

0

당신은 그 라인을 따라 뭔가를 시도해야합니다 :

temp_board[temp_board[field_list] == 0] = level 
+0

temp_board [field_list] == ​​0 temp_board의 크기보다 작은 마스크를 반환합니다 –

1

난 내가 당신의 질문에 모든 세부 사항에 따라 확실하지 않다. 만약 내가 그것을 정확하게 이해한다면, 이것은 단순한 Numpy 색인 생성처럼 보인다. 아래의 코드는 배열 (A)에 0을 넣고 그 배열을 찾으면 'level'로 바꿉니다.

import numpy as NP 
A = NP.random.randint(0, 10, 20).reshape(5, 4) 
level = 999 
ndx = A==0 
A[ndx] = level