๊ฐœ๋…

NumPy์˜ fancy indexing ๋˜๋Š” advanced indexing์€ ๋ฐฐ์—ด์—์„œ ๋‹จ์ผ ๊ฐ’์ด ์•„๋‹ˆ๋ผ ์—ฌ๋Ÿฌ ๊ฐ’์„ ๋™์‹œ์— ์„ ํƒํ•˜๊ฑฐ๋‚˜ ์กฐ์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ•๋ ฅํ•œ ์ธ๋ฑ์‹ฑ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ์ ์ธ ์ธ๋ฑ์‹ฑ(์ •์ˆ˜ ์ธ๋ฑ์‹ฑ์ด๋‚˜ ์Šฌ๋ผ์ด์‹ฑ)๊ณผ ๋‹ฌ๋ฆฌ, fancy indexing์€ ๋ฐฐ์—ด์ด๋‚˜ ๋ฆฌ์ŠคํŠธ๋กœ ์ธ๋ฑ์Šค๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ์›ํ•˜๋Š” ์œ„์น˜์˜ ์—ฌ๋Ÿฌ ๊ฐ’์„ ํ•œ ๋ฒˆ์— ์„ ํƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ธฐ๋Šฅ์€ ๋งค์šฐ ์œ ์—ฐํ•˜๊ณ , ๋ณต์žกํ•œ ๋ฐฐ์—ด์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์„ ํƒํ•˜๋Š” ๋ฐ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

๊ธฐ๋ณธ์ ์ธ ์ธ๋ฑ์‹ฑ๊ณผ์˜ ์ฐจ์ด์ 

๊ธฐ๋ณธ์ ์ธ ์ธ๋ฑ์‹ฑ์€ ๋‹จ์ผ ์ธ๋ฑ์Šค ๋˜๋Š” ์Šฌ๋ผ์ด์Šค๋กœ ๋ฐฐ์—ด์˜ ์›์†Œ๋ฅผ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด:

arr = np.array([10, 20, 30, 40, 50])
print(arr[2])   # ๊ฒฐ๊ณผ: 30 (๋‹จ์ผ ์ธ๋ฑ์Šค)
print(arr[1:3]) # ๊ฒฐ๊ณผ: [20 30] (์Šฌ๋ผ์ด์Šค)

ํ•˜์ง€๋งŒ fancy indexing์—์„œ๋Š” ๋ฐฐ์—ด์ด๋‚˜ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณต์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ์—ฌ๋Ÿฌ ๊ฐ’์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Fancy indexing ์‚ฌ์šฉ๋ฒ•

  1. ์ •์ˆ˜ ๋ฐฐ์—ด๋กœ ์ธ๋ฑ์‹ฑ

    ์˜ˆ์‹œ:

    arr = np.array([10, 20, 30, 40, 50])
    indices = [1, 3, 4]
    print(arr[indices])  # ๊ฒฐ๊ณผ: [20 40 50]
    

    2์ฐจ์› ๋ฐฐ์—ด์—์„œ๋„ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

    row_indices์™€ col_indices์˜ ๊ธธ์ด๋Š” ๊ฐ™์•„์•ผ ํ•œ๋‹ค.

    arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    row_indices = [0, 2]
    col_indices = [1, 2]
    print(arr2d[row_indices, col_indices])  # ๊ฒฐ๊ณผ: [2 9]
    

    ์—ฌ๊ธฐ์„œ arr2d[0, 1]์€ 2, arr2d[2, 2]๋Š” 9์ด๋ฏ€๋กœ [2, 9]๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

  2. ๋ถˆ๋ฆฌ์–ธ ๋งˆ์Šคํฌ ๋ฐฐ์—ด๋กœ ์ธ๋ฑ์‹ฑ

    ์˜ˆ์‹œ:

    arr = np.array([1, 2, 3, 4, 5])
    mask = arr > 3  # ์กฐ๊ฑด ์ƒ์„ฑ: [False, False, False, True, True]
    print(arr[mask])  # ๊ฒฐ๊ณผ: [4 5]
    
  3. ๋‹ค์ฐจ์› ๋ฐฐ์—ด์—์„œ์˜ fancy indexing

    ์˜ˆ์‹œ:

    arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    row_indices = [0, 1, 2]
    col_indices = [2, 1, 0]
    print(arr2d[row_indices, col_indices])  # ๊ฒฐ๊ณผ: [3 5 7]
    

    ์—ฌ๊ธฐ์„œ arr2d[0, 2]๋Š” 3, arr2d[1, 1]์€ 5, arr2d[2, 0]์€ 7์ž…๋‹ˆ๋‹ค.

Fancy indexing๊ณผ ๊ธฐ๋ณธ ์ธ๋ฑ์‹ฑ์˜ ์ฐจ์ด์ 

์˜ˆ์‹œ:

arr = np.array([10, 20, 30, 40, 50])
fancy_result = arr[[1, 3]]
fancy_result[0] = 100
print(arr)  # ๊ฒฐ๊ณผ: [10 20 30 40 50] (์›๋ณธ ๋ฐฐ์—ด์€ ์ˆ˜์ •๋˜์ง€ ์•Š์Œ)

Fancy indexing์„ ์ด์šฉํ•œ ํ• ๋‹น

Fancy indexing์„ ์ด์šฉํ•ด ์„ ํƒํ•œ ๊ฐ’๋“ค์„ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

arr = np.array([10, 20, 30, 40, 50])
arr[[1, 3, 4]] = 99  # 1, 3, 4 ๋ฒˆ์งธ ์›์†Œ๋ฅผ 99๋กœ ๋ณ€๊ฒฝ
print(arr)  # ๊ฒฐ๊ณผ: [10 99 30 99 99]

๊ฒฐ๋ก 

NumPy์˜ fancy indexing์€ ๋งค์šฐ ์œ ์—ฐํ•œ ๋ฐฉ์‹์œผ๋กœ ๋ฐฐ์—ด์˜ ์—ฌ๋Ÿฌ ์š”์†Œ๋ฅผ ๋™์‹œ์— ์„ ํƒํ•˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค๋‹ˆ๋‹ค. ๋ณต์žกํ•œ ๋ฐฐ์—ด์—์„œ ํŠน์ • ํŒจํ„ด์„ ๋”ฐ๋ผ ๊ฐ’์„ ์ถ”์ถœํ•˜๊ฑฐ๋‚˜ ์กฐ์ž‘ํ•ด์•ผ ํ•  ๋•Œ ๋งค์šฐ ์œ ์šฉํ•œ ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.