Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

NumPy 数组切片


数组切片

Python 中的切片是指从给定索引到另一个给定索引取元素。

我们使用切片而不是索引,形式为:[start:end]

我们还可以定义步长,形式为:[start:end:step]

如果不指定 start,则默认为 0

如果不指定 end,则默认为该维度的数组长度

如果不指定 step,则默认为 1

示例

从以下数组中切片索引 1 到索引 5 的元素

import numpy as np

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

print(arr[1:5])
动手试试 »

注意:结果包含起始索引,但不包含结束索引。

示例

切片索引 4 到数组末尾的元素

import numpy as np

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

print(arr[4:])
动手试试 »

示例

切片从开头到索引 4(不包含)的元素

import numpy as np

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

print(arr[:4])
动手试试 »


负向切片

使用减号运算符来引用从末尾开始的索引

示例

从末尾的索引 3 切片到末尾的索引 1

import numpy as np

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

print(arr[-3:-1])
动手试试 »

步长

使用step值来确定切片的步长

示例

从索引 1 到索引 5 返回每隔一个元素

import numpy as np

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

print(arr[1:5:2])
动手试试 »

示例

从整个数组返回每隔一个元素

import numpy as np

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

print(arr[::2])
动手试试 »

二维数组切片

示例

从第二个元素开始,切片索引 1 到索引 4(不包含)的元素

import numpy as np

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

print(arr[1, 1:4])
动手试试 »

注意:请记住,第二个元素的索引为 1。

示例

从两个元素中,返回索引 2

import numpy as np

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

print(arr[0:2, 2])
动手试试 »

示例

从两个元素中,切片索引 1 到索引 4(不包含),这将返回一个二维数组

import numpy as np

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

print(arr[0:2, 1:4])
动手试试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.