Срезы и индексация массивов
Выбирайте отдельные элементы, строки, столбцы и подмассивы многомерных массивов с помощью целочисленной индексации и срезов
«Срезы и индексация массивов» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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]) # 30Slicing 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 column2-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 2np.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] -- unchanged3-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 3Assigning 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 vectorQuick 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) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «Срезы и индексация массивов»?
Выбирайте отдельные элементы, строки, столбцы и подмассивы многомерных массивов с помощью целочисленной индексации и срезов Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Срезы и индексация массивов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Создание массивов NumPy
- Атрибуты и проверка массивов
- Поэлементная арифметика
- Срезы и индексация массивов