如何在Python中从Numpy数组中选择元素?
在本文中,我们将向您展示如何在 Python 中从 NumPy 数组中选择元素。
Python 中的 Numpy 数组
顾名思义,NumPy 数组是 NumPy 库的中心数据结构。该库的名称是“Numeric Python”或“Numerical Python”的缩写。
换句话说,NumPy 是一个 Python 库,是 Python 科学计算的基础。其中一个工具是高性能多维数组对象,它是一种用于高效数组和矩阵计算的强大数据结构。
我们可以一次从 Numpy 数组中选择一个元素或一个子数组。现在我们看到以下从 Numpy 数组中选择元素的方法。
- 选择单个 NumPy 数组元素
- 使用切片从 NumPy 数组中选择子数组
- 仅通过给出停止值来选择/访问子数组
- 仅通过给出起始值来选择/访问子数组
方法 1 - 选择单个 NumPy 数组元素
这些 ndarray 的每个元素都可以通过它们的索引号来访问。
算法(步骤)
以下是执行所需任务所需遵循的算法/步骤 -
使用 import 关键字,导入带有别名 (np) 的 numpy 模块。
使用numpy.array()函数(返回一个ndarray。ndarray是满足给定要求的数组对象),通过传递一维数组来创建numpy数组数组作为它的参数。
使用正索引访问索引 1 处的 NumPy 数组元素并打印 它。
Use negative indexing to access the NumPy array element at index -1 i.e the last element of an array and print 它。
Negative Indexing(): Python allows for "indexing from the end," i.e., negative indexing. This means that the last value in a sequence has an index of -1, the second last has an index of -2, and so on. When you want to pick values from the end (right side) of an iterable, you can utilize negative indexing to your benefit.登录后复制