杰瑞科技汇

NumPy切片如何高效操作多维数组?

Of course! Let's dive deep into NumPy slicing. It's a fundamental and powerful feature that allows you to extract portions of arrays, similar to Python's built-in lists, but with much more power and speed for multi-dimensional arrays.

NumPy切片如何高效操作多维数组?-图1
(图片来源网络,侵删)

The Core Concept: The start:stop:step Syntax

At its heart, NumPy slicing uses the same syntax as Python lists:

array[start:stop:step]
  • start: The index where the slice begins (inclusive). If omitted, it defaults to 0.
  • stop: The index where the slice ends (exclusive). If omitted, it defaults to the end of the dimension.
  • step: The amount to "jump" between indices. If omitted, it defaults to 1.

Slicing 1-Dimensional Arrays

This is the simplest case and works almost exactly like a Python list.

Let's create a 1D array:

import numpy as np
a = np.arange(10) # Creates array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(f"Original array: {a}\n")

Examples:

NumPy切片如何高效操作多维数组?-图2
(图片来源网络,侵删)
  • Get the first 5 elements (from index 0 up to, but not including, 5):

    print(a[0:5])   # Output: [0 1 2 3 4]
    print(a[:5])    # Output: [0 1 2 3 4]  (start is optional if it's 0)
  • Get elements from index 3 to the end:

    print(a[3:])    # Output: [3 4 5 6 7 8 9] (stop is optional to go to the end)
  • Get every other element (using a step of 2):

    print(a[::2])   # Output: [0 2 4 6 8]
  • Reverse the array (using a step of -1):

    NumPy切片如何高效操作多维数组?-图3
    (图片来源网络,侵删)
    print(a[::-1])  # Output: [9 8 7 6 5 4 3 2 1 0]

Slicing Multi-Dimensional Arrays

This is where NumPy slicing shines. You apply the start:stop:step syntax to each dimension separately, separated by a comma.

The syntax is: array[dimension1_slice, dimension2_slice, ...]

Let's create a 2D array (a matrix):

import numpy as np
# Create a 3x4 matrix
b = np.arange(12).reshape(3, 4)
print(f"Original 2D array:\n{b}\n")
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

Examples:

  • Get the entire first row:

    # Slice on the first dimension (rows), get all elements from the first row
    # Slice on the second dimension (columns), get all elements
    print(b[0, :])
    # Output: [0 1 2 3]
  • Get the entire second column:

    # Slice on the first dimension, get all rows
    # Slice on the second dimension, get the element at index 1
    print(b[:, 1])
    # Output: [ 1  5  9]
  • Get a sub-matrix (from row 1 to 2, and column 2 to 3):

    # Rows: start at index 1, go up to (but not including) index 3. So, rows 1 and 2.
    # Columns: start at index 2, go up to (but not including) index 4. So, columns 2 and 3.
    print(b[1:3, 2:4])
    # Output:
    # [[ 6  7]
    #  [10 11]]
  • Get every other row and every other column:

    # Rows: step of 2 (rows 0 and 2)
    # Columns: step of 2 (columns 0 and 2)
    print(b[::2, ::2])
    # Output:
    # [[ 0  2]
    #  [ 8 10]]

Slicing Higher-Dimensional Arrays (e.g., 3D)

The logic extends perfectly to 3D or higher dimensions. The comma just separates more slices.

Let's create a 3D array (a "cube" of numbers):

import numpy as np
c = np.arange(24).reshape(2, 3, 4)
print(f"Original 3D array shape: {c.shape}\n")
# Shape is (2, 3, 4), meaning 2 layers, each with 3 rows and 4 columns.
# Layer 0:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# Layer 1:
# [[12 13 14 15]
#  [16 17 18 19]
#  [20 21 22 23]]

Examples:

  • Get the first layer (index 0):

    # Slice on the first dimension (layers), get the first one.
    # Get all rows and columns from that layer.
    print(c[0, :, :])
    # Output is the 3x4 matrix for layer 0 shown above.
  • Get the second row from all layers:

    # Get all layers, then the second row (index 1), then all columns.
    print(c[:, 1, :])
    # Output:
    # [[ 4  5  6  7]
    #  [16 17 18 19]]
  • Get a single element:

    # Layer 1, Row 2, Column 3
    print(c[1, 2, 3]) # Output: 23

Important Distinction: Slicing vs. Indexing

This is a critical concept in NumPy.

Operation What it Does Example (b = np.arange(12).reshape(3,4)) Result Type Memory
Slicing Creates a view of the original array. view = b[1:, 1:] numpy.ndarray Shared. Changes to the view affect the original.
Integer Indexing Selects specific elements. Can be used to create a copy. element = b[0, 0] Python int or numpy.int64 Copied (scalar).
Fancy Indexing Selects a list of indices. Creates a copy. copy = b[[0, 2], [1, 3]] numpy.ndarray Copied.

Example: The "View" vs. "Copy" Behavior

import numpy as np
a = np.arange(10)
print(f"Original array a: {a}")
# Slicing creates a VIEW
view_slice = a[2:6]
print(f"\nView slice (a[2:6]): {view_slice}")
# Modify the view
view_slice[0] = -99
print(f"\nOriginal array a after modifying view: {a}")
print(f"Notice that a[2] also changed! The view shares memory with the original.")

Output:

Original array a: [0 1 2 3 4 5 6 7 8 9]
View slice (a[2:6]): [2 3 4 5]
Original array a after modifying view: [  0   1 -99   3   4   5   6   7   8   9]
Notice that a[2] also changed! The view shares memory with the original.

How to Force a Copy

If you need a new, independent array, you must explicitly create a copy using the .copy() method.

import numpy as np
a = np.arange(10)
print(f"Original array a: {a}")
# Create a COPY of a slice
copy_slice = a[2:6].copy()
print(f"\nCopy slice (a[2:6].copy()): {copy_slice}")
# Modify the copy
copy_slice[0] = -99
print(f"\nOriginal array a after modifying copy: {a}")
print(f"The original array is unchanged. The copy is independent.")

Output:

Original array a: [0 1 2 3 4 5 6 7 8 9]
Copy slice (a[2:6].copy()): [2 3 4 5]
Original array a after modifying copy: [0 1 2 3 4 5 6 7 8 9]
The original array is unchanged. The copy is independent.

Summary Table

Goal Syntax Example
Slice 1D arr[start:stop:step] arr[1:5:2]
Slice all in dim arr[:, 1] (get all rows, column 1)
Slice multi-dim arr[dim1_slice, dim2_slice, ...] arr[1:3, ::2]
Reverse arr[::-1] arr[::-1, ::-1]
Get single element arr[i, j, k] arr[0, 0, 0]
Create a copy arr[...].copy() arr[1:, 1:].copy()
分享:
扫描分享到社交APP
上一篇
下一篇