2014-10-29 2 views
2

ndarray을 여러 줄로 한 줄로 자르는 방법은 무엇입니까? 다음 스 니펫에서 마지막 행을 확인하십시오. 이것은 너무 기본적인 것 같지만 놀람을줍니다 ...하지만 왜?ndarray에서 여러 치수 잘라 내기

import numpy as np 

# create 4 x 3 array 
x = np.random.rand(4, 3) 

# create row and column filters 
rows = np.array([True, False, True, False]) 
cols = np.array([True, False, True]) 

print(x[rows, :].shape == (2, 3)) # True ... OK 
print(x[:, cols].shape == (4, 2)) # True ... OK 
print(x[rows][:, cols].shape == (2, 2)) # True ... OK 
print(x[rows, cols].shape == (2, 2)) # False ... WHY??? 

답변

4
rows 이후

cols 당신이 할 때, 부울 배열 인 :

x[rows, cols] 

이 같은 수 있습니다 :

x[[0, 2], [0, 2]] 

이 가치있는 촬영 :입니다

x[np.where(rows)[0], np.where(cols)[0]] 

위치는 (0, 0)이고 (2, 2)입니다. 반면에, 일 :

x[rows][:, cols] 

작품처럼 :

x[[0, 2]][:, [0, 2]] 

이 예에서 모양 (2, 2)를 반환.

+1

자세한 내용은 다음을 참조하십시오. http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays – ballsatballsdotballs