Python 访问多维NumPy数组的不同列的程序

Python 访问多维NumPy数组的不同列的程序

NumPy 是Python中用于计算数值数据的最强大的库。它提供了多维数组以及与数组一起使用的不同函数和模块的集合。其高效的数组操作、广播功能以及与其他库的集成使其成为数据操作、分析和建模任务的首选。以下是NumPy库的主要功能和功能。

  • 多维数组

  • 数组创建

  • 数组操作

  • 索引和切片

  • 矢量化操作

  • 数值例程

  • 与其他库的集成

  • 性能

  • 开源和社区支持

创建一个数组

在NumPy库中,我们有称为 array()reshape() 的函数。其中 array() 函数在一维中创建数组, reshape() 函数将给定的元素列表转换为定义的形状。

示例

在此示例中,我们将使用 array() 函数通过传递元素列表和 reshape() 函数通过传递数组的形状即行数和列数来创建2维数组。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))

输出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2

访问多维数组的不同列有几种方法。让我们详细看一下每一种方法。

使用基本索引

我们可以使用带方括号的基本索引来访问NumPy数组的特定列,在括号内指定列索引以检索所需的列或列。

示例

在这个例子中,我们使用基本索引方法应用于2维数组,以访问数组的第一列,使用 [:,0] ,然后返回2维数组的第一列元素。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The first column of the array:",arr[:,0])

输出

array: [[90 56 14 22  1]
[21  7 12  5 24]]
dimension of the array: 2
The first column of the array: [90 21]

使用切片技术

切片用于访问给定输入数组中的一系列列,我们需要指定起始索引和结束索引,以及以冒号分隔的步长。

示例

在这个示例中,我们使用切片技术通过应用[:,3:5]来访问输入数组的中间两列,并将中间列的元素作为输出返回。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The middle columns of the array:",arr[:,3:5])

输出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2
The middle columns of the array: [[22  1]
 [ 5 24]]

使用精确索引

精确索引允许我们通过提供一组列索引来访问特定的列。当我们想要访问非连续的列或特定的列子集时,我们可以使用这种方法。

示例

这个例子中,我们通过使用精确索引和索引列表 [:,0,4] 来访问第一列和最后一列,然后返回数组的最后一列和第一列的元素。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The first and last columns of the array:",arr[:,[0,4]])

输出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2
The first and last columns of the array: [[90  1]
 [21 24]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程