0Pricing
Pandas & NumPy Academy · 강의

배열 슬라이싱과 인덱싱

다차원 배열에서 정수 및 슬라이스 표기법을 사용해 개별 원소, 행, 열, 부분 배열을 선택합니다.

배열 슬라이싱과 인덱싱은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Integer Indexing in 1-D Arrays

A 1-D array is indexed just like a list: a[0] is first, a[-1] is last. Indexing returns a single scalar, and negative numbers count from the end.

import numpy as np

a = np.array([10, 20, 30, 40, 50])
print(a[0])    # 10
print(a[-1])   # 50
print(a[2])    # 30

Slicing 1-D Arrays

Slices use start:stop:step like lists, but a NumPy slice returns a view — no copy. Change the slice and you change the original, so use .copy() when needed.

import numpy as np

a = np.arange(10)  # [0 1 2 3 4 5 6 7 8 9]
print(a[2:7])      # [2 3 4 5 6]
print(a[::2])      # [0 2 4 6 8]
print(a[::-1])     # [9 8 7 6 5 4 3 2 1 0]

Indexing 2-D Arrays

For 2-D arrays, use comma syntax: a[row, col]. A lone colon means everything along that axis, so a[0, :] grabs a whole row and a[:, 1] a whole column.

import numpy as np

m = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

print(m[1, 2])     # 6  (row 1, col 2)
print(m[0, :])     # [1 2 3]  first row
print(m[:, 1])     # [2 5 8]  second column

2-D Array Slicing

Give two slices to grab a rectangular block: a[0:2, 1:3] takes those rows and columns. The result is a view, so edits flow back to the original.

import numpy as np

m = np.arange(16).reshape(4, 4)
print(m)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]
#  [12 13 14 15]]

print(m[1:3, 1:3])
# [[ 5  6]
#  [ 9 10]]

Boolean Indexing

Pass a boolean array to keep only the elements marked True. This boolean indexing always returns a copy and is the standard way to filter data.

import numpy as np

a = np.array([3, 7, 2, 9, 1, 6])
mask = a > 4
print(mask)     # [False  True False  True False  True]
print(a[mask])  # [7 9 6]

# Equivalent one-liner
print(a[a > 4])  # [7 9 6]

Fancy Indexing with Integer Arrays

Fancy indexing lets you pick elements at any positions with a list of integers — in any order, even repeating them. It always returns a copy.

import numpy as np

a = np.array([10, 20, 30, 40, 50])
idx = [4, 1, 3]
print(a[idx])    # [50 20 40]

# Selecting specific rows from a 2D array
m = np.arange(20).reshape(4, 5)
print(m[[0, 2], :])  # rows 0 and 2

np.where for Conditional Selection

np.where(condition, x, y) picks from x where the condition is True and from y where it's False — a fast, loop-free way to choose values per element.

import numpy as np

a = np.array([5, -3, 8, -1, 2])
result = np.where(a > 0, a, 0)  # keep positives, zero negatives
print(result)  # [5 0 8 0 2]

# np.where with one argument returns indices of True elements
idx = np.where(a > 0)
print(idx)     # (array([0, 2, 4]),)

Slices Are Views — Gotcha!

Heads up: since slices are views, editing one edits the original array too. Need an independent piece? Call .copy() on the slice first. ⚠️

import numpy as np

original = np.arange(6)
view = original[2:5]   # view, not copy
view[:] = 99
print(original)  # [ 0  1 99 99 99  5]  -- original changed!

safe = original[2:5].copy()  # true copy
safe[:] = 0
print(original)  # [ 0  1 99 99 99  5]  -- unchanged

3-D Array Indexing

Arrays can have any number of dimensions. For a 3-D array you index with three positions: a[depth, row, col] — common when handling batches of images.

import numpy as np

t = np.arange(24).reshape(2, 3, 4)
print(t.shape)       # (2, 3, 4)
print(t[0, :, :])    # first 'plane' -- shape (3, 4)
print(t[1, 2, 3])    # scalar at depth 1, row 2, col 3

Assigning Values Through Indexing

Any indexing form works on the left side of an = to change values in place — slices, masks, or fancy indices. Assign a scalar and NumPy spreads it to every spot.

import numpy as np

a = np.zeros(8)
a[2:5] = 1.0          # slice assignment
print(a)  # [0. 0. 1. 1. 1. 0. 0. 0.]

a[a == 0] = -1.0      # boolean assignment
print(a)  # [-1. -1.  1.  1.  1. -1. -1. -1.]

Ellipsis and np.newaxis

np.newaxis (or None) adds a size-1 axis, turning a (5,) array into a (5, 1) column vector — a common setup before broadcasting.

import numpy as np

t = np.ones((2, 3, 4))
print(t[..., 0].shape)   # (2, 3) -- last axis fixed at 0

a = np.array([1, 2, 3])
print(a.shape)                 # (3,)
print(a[:, np.newaxis].shape)  # (3, 1) column vector

Quick Check

Test your understanding of NumPy array slicing and indexing from this lesson.

Lesson Recap

Well done! Slices are views that share memory, boolean indexing filters and copies, and fancy indexing grabs any elements you name. Next: universal functions.

자주 묻는 질문

“배열 슬라이싱과 인덱싱” 강의는 무료인가요?

네 — “배열 슬라이싱과 인덱싱” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“배열 슬라이싱과 인덱싱”에서 뭘 배우나요?

다차원 배열에서 정수 및 슬라이스 표기법을 사용해 개별 원소, 행, 열, 부분 배열을 선택합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“배열 슬라이싱과 인덱싱” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. NumPy 배열 만들기
  2. 배열 속성과 검사
  3. 원소별 산술 연산
  4. 배열 슬라이싱과 인덱싱
← Pandas & NumPy Academy(으)로 돌아가기