Numpy. section6 : ndarray의 인덱싱과 슬라이싱. Lec26. bool ndarray로 인덱싱하기

timekeeep·2023년 3월 4일
0

Numpy

목록 보기
25/28

[1] bool ndarray로 인덱싱하기

  • True는 이 값을 뽑겠다, False는 이 값을 뽑지 않겠다를 의미함
  • a와 b_indices의 shape이 동일해야 함
  • 행렬 케이스에서는 결과를 벡터로 만든다
  • np.nonzero, np.where은 boolean값일 경우에 True인 값들의 인덱스를 반환함


a = np.random.randint(-2, 3, size = (3,3))

u_nonzero = a[np.nonzero(a)]
u_where = a[np.where(a)]
u_bool = a[a != 0]

print(f"a: \n{a}\n")
print(f"using nonzero: \n{u_nonzero}")
print(f"using where: \n{u_where}")
print(f"using bool ndarray: \n{u_bool}")
import numpy as np

a = np.arange(5)
print(f"ndarray: \n{a}")

b_indices = np.array([True, False, True, False, True])
print(f"b_indices: \n{b_indices}\n")

print(f"a[b_indices]: \n{a[b_indices]}")

#

a = np.random.randint(0, 20, (10,))
print(f"ndarray: \n{a}")

b_indices = (a%2 == 0)
print(f"b_indices: \n{b_indices}\n")

print(f"a[b_indices]: \n{a[b_indices]}")

'''
ndarray:
[16 10 14  7  8 11 14  3 10  3]
b_indices:
[ True  True  True False  True False  True False  True False]

a[b_indices]:
[16 10 14  8 14 10]'''

# 행렬 케이스

a = np.random.randint(0, 20, (2,2))
print(f"ndarray: \n{a}")

b_indices = np.array([[True, False], [False, True]])
print(f"b_indices: \n{b_indices}\n")

print(f"a[b_indices]: \n{a[b_indices]}")

'''ndarray:
[[ 6  6]
 [10  9]]
b_indices:
[[ True False]
 [False  True]]

a[b_indices]:
[6 9]'''


#

a = np.random.randint(0,20, (3,4))
print(f"ndarray: \n{a}")

b_indices = (a > 10)
print(f"b_indices: \n{b_indices}\n")

print(f"a[b_indices]: \n{a[b_indices]}")


# vector

a = np.array([True, False, True, False])

nonzero = np.nonzero(a)
where = np.where(a)

print(f"a: \n{a}\n")
print(f"nonzero: \n{nonzero}")
print(f"where: \n{where}")

# matrix

a = np.array([True, False], [True, False])

nonzero = np.nonzero(a)
where = np.where(a)

print(f"a: \n{a}\n")
print(f"nonzero: \n{nonzero}")
print(f"where: \n{where}")

# 3rd-dimension

a = np.array([[[True, False, True], 
               [True, False, False]],
               
               [[False, True, False],
                [True, False, True]]])

nonzero = np.nonzero(a)
where = np.where(a)

print(f"a: \n{a}\n")
print(f"nonzero: \n{nonzero}")
print(f"where: \n{where}")


#

a = np.random.randint(-2, 3, size = (3,3))

u_nonzero = a[np.nonzero(a)]
u_where = a[np.where(a)]
u_bool = a[a != 0]

print(f"a: \n{a}\n")
print(f"using nonzero: \n{u_nonzero}")
print(f"using where: \n{u_where}")
print(f"using bool ndarray: \n{u_bool}")

#

a = np.random.randint(-2, 3, size = (3,3))

u_nonzero = a[np.nonzero(a > 0)]
u_where = a[np.where(a > 0)]
u_bool = a[a > 0]

print(f"a: \n{a}\n")
print(f"using nonzero: \n{u_nonzero}")
print(f"using where: \n{u_where}")
print(f"using bool ndarray: \n{u_bool}")
profile
Those who are wise will shine like the brightness of the heavens, and those who lead many to righteousness, like the stars for ever and ever

0개의 댓글