Python Numpy入门基础(二)数组操作

简介: Python Numpy入门基础(二)数组操作


脚本设置

Python Numpy入门基础(二)数组操作

Hann Yang2023-07-29 11:30:55

阅读量1.8k

点赞数 38

分类专栏Python文章标签pythonnumpy

版权

186 篇文章63 订阅

订阅专栏

入门基础(二)

NumPy是Python中一个重要的数学运算库,它提供了了一组多维数组对象和一组用于操作这些数组的函数。以下是一些NumPy的主要特点:

  1. 多维数组对象:NumPy的核心是ndarray对象,它是一个多维数组对象,可以容纳任意数据类型。
  2. 矢量化操作:使用NumPy的函数,可以对整个数组进行操作,而不需要显式循环。
  3. 广播:NumPy的广播机制允许对不同形状的数组执行算术操作,而无需进行显式循环或手动对齐。
  4. 易于扩展:NumPy可以用C或C++扩展,以加速大型数值计算任务。
  5. 强大的函数库:NumPy提供了许多用于线性代数、傅里叶分析、随机数生成等领域的函数。
  6. 易于使用:NumPy与Python的内置数据结构无缝集成,因此可以轻松地将Python代码转换为使用NumPy。

数组操作

组索引和切片

索引从0开始,索引值不能超过长度,否则会报IndexError错误。

一维数组的索引和切片
1. >>> import numpy as np
2. >>> a = np.array([1,2,3,4,5])
3. >>> a[2]
4. 3
5. >>> a[1:4:2]
6. array([2, 4])
7. >>> a[1:3]
8. array([2, 3])
9. >>> a[0::2]
10. array([1, 3, 5])
11. >>> a[5]
12. Traceback (most recent call last):
13.   File "<pyshell#15>", line 1, in <module>
14.     a[5]
15. IndexError: index 5 is out of bounds for axis 0 with size 5
多维数组的索引
1. >>> import numpy as np
2. >>> a = np.arange(24).reshape((2,3,4))
3. >>> a
4. array([[[ 0,  1,  2,  3],
5.         [ 4,  5,  6,  7],
6.         [ 8,  9, 10, 11]],
7. 
8.        [[12, 13, 14, 15],
9.         [16, 17, 18, 19],
10.         [20, 21, 22, 23]]])
11. >>> a[1,2,3]
12. 23
13. >>> a[-1,-2,-3]
14. 17
15. >>> a[0,2,2]
16. 10
17. >>> a[0,3,3]
18. Traceback (most recent call last):
19.   File "<pyshell#12>", line 1, in <module>
20.     a[0,3,3]
21. IndexError: index 3 is out of bounds for axis 1 with size 3
22.
多维数组切片
1. >>> import numpy as np
2. >>> a = np.arange(24).reshape((2,3,4)) + 1
3. >>> a
4. array([[[ 1,  2,  3,  4],
5.         [ 5,  6,  7,  8],
6.         [ 9, 10, 11, 12]],
7. 
8.        [[13, 14, 15, 16],
9.         [17, 18, 19, 20],
10.         [21, 22, 23, 24]]])
11. >>> a[:1,2]
12. array([[ 9, 10, 11, 12]])
13. >>> a[:,1:3,:]
14. array([[[ 5,  6,  7,  8],
15.         [ 9, 10, 11, 12]],
16. 
17.        [[17, 18, 19, 20],
18.         [21, 22, 23, 24]]])
19. >>> a[:,:,::2]
20. array([[[ 1,  3],
21.         [ 5,  7],
22.         [ 9, 11]],
23. 
24.        [[13, 15],
25.         [17, 19],
26.         [21, 23]]])
27. >>> a[:,:,1::2]
28. array([[[ 2,  4],
29.         [ 6,  8],
30.         [10, 12]],
31. 
32.        [[14, 16],
33.         [18, 20],
34.         [22, 24]]])
35. >>> a[1:3,:,:]
36. array([[[13, 14, 15, 16],
37.         [17, 18, 19, 20],
38.         [21, 22, 23, 24]]])
39. >>> a[1:3,1:3,:]
40. array([[[17, 18, 19, 20],
41.         [21, 22, 23, 24]]])
42. >>> a[1:3,1:3,1:3]
43. array([[[18, 19],
44.         [22, 23]]])
通过布尔数组访问数组元素
1. >>> import numpy as np
2. >>> a = np.array([1, 2, 3, 4, 5])
3. >>> b = np.array([True, False, True, False, True])
4. >>> a[b]
5. array([1, 3, 5])
6. >>> b = np.array([False, True, False, True, False])
7. >>> a[b]
8. array([2, 4])
9. >>> b = a<=3
10. >>> a[b]
11. array([1, 2, 3])
12. >>> b = a%2==0
13. >>> a[b]
14. array([2, 4])
15. >>> b = a%2==1
16. >>> a[b]
17. array([1, 3, 5])

数组的整体操作

数组的拼接

在 NumPy 中,可以使用多种方法来拼接数组。以下是一些常用的方法:

numpy.concatenate()

这个函数用于连接两个数组,沿指定的轴在末尾添加第二个数组的元素。

1. >>> a = np.array([[1, 2], [3, 4]])
2. >>> b = np.array([[5, 6]])
3. >>> np.concatenate((a, b), axis=0)
4. array([[1, 2],
5.       [3, 4],
6.       [5, 6]])
7. >>> np.concatenate((a, b.T), axis=1)
8. array([[1, 2, 5],
9.       [3, 4, 6]])
10. >>> np.concatenate((a, b), axis=None)
11. array([1, 2, 3, 4, 5, 6])
numpy.vstack()

这个函数用于垂直方向拼接数组,即行方向添加第二个数组的元素。

1. >>> a = np.array([1, 2, 3])
2. >>> b = np.array([4, 5, 6])
3. >>> np.vstack((a,b))
4. array([[1, 2, 3],
5.       [4, 5, 6]])
6. 
7. >>> a = np.array([[1], [2], [3]])
8. >>> b = np.array([[4], [5], [6]])
9. >>> np.vstack((a,b))
10. array([[1],
11.       [2],
12.       [3],
13.       [4],
14.       [5],
15.       [6]])
numpy.hstack()

这个函数用于水平方向拼接数组,即列方向添加第二个数组的元素。

1. >>> a = np.array((1,2,3))
2. >>> b = np.array((4,5,6))
3. >>> np.hstack((a,b))
4. array([1, 2, 3, 4, 5, 6])
5. >>> a = np.array([[1],[2],[3]])
6. >>> b = np.array([[4],[5],[6]])
7. >>> np.hstack((a,b))
8. array([[1, 4],
9.        [2, 5],
10.        [3, 6]])
numpy.row_stack()

这个函数是vstack的alias,别名就是同一个函数。

1. >>> import numpy as np
2. >>> a = np.array([[1, 2], [3, 4]])
3. >>> b = np.array([[5, 6]])
4. >>> np.row_stack((a, b))
5. array([[1, 2],
6.        [3, 4],
7.        [5, 6]])

在使用这些函数时,需要确保拼接的数组具有相同的维度,或者在使用 numpy.column_stack() 时具有相同的列数。如果维度不同,可以使用 numpy.reshape() 函数对数组进行重塑。

数组的翻转

在 NumPy 中,也有多种方法可以翻转数组。以下是一些常用的方法:

numpy.flip()

这个函数用于沿指定的轴翻转数组。

   Examples

   --------

   >>> A = np.arange(8).reshape((2,2,2))

   >>> A

   array([[[0, 1],

           [2, 3]],

          [[4, 5],

           [6, 7]]])

   >>> np.flip(A, 0)

   array([[[4, 5],

           [6, 7]],

          [[0, 1],

           [2, 3]]])

   >>> np.flip(A, 1)

   array([[[2, 3],

           [0, 1]],

          [[6, 7],

           [4, 5]]])

   >>> np.flip(A)

   array([[[7, 6],

           [5, 4]],

          [[3, 2],

           [1, 0]]])

   >>> np.flip(A, (0, 2))

   array([[[5, 4],

           [7, 6]],

          [[1, 0],

           [3, 2]]])

   >>> A = np.random.randn(3,4,5)

   >>> np.all(np.flip(A,2) == A[:,:,::-1,...])

   True

numpy.flipud()

这个函数用于垂直方向翻转数组,即行方向翻转。

   Examples

   --------

   >>> A = np.diag([1.0, 2, 3])

   >>> A

   array([[1.,  0.,  0.],

          [0.,  2.,  0.],

          [0.,  0.,  3.]])

   >>> np.flipud(A)

   array([[0.,  0.,  3.],

          [0.,  2.,  0.],

          [1.,  0.,  0.]])

   

   >>> A = np.random.randn(2,3,5)

   >>> np.all(np.flipud(A) == A[::-1,...])

   True

   

   >>> np.flipud([1,2])

   array([2, 1])

numpy.fliplr()

这个函数用于水平方向翻转数组,即列方向翻转。

   Examples

   --------

   >>> A = np.diag([1.,2.,3.])

   >>> A

   array([[1.,  0.,  0.],

          [0.,  2.,  0.],

          [0.,  0.,  3.]])

   >>> np.fliplr(A)

   array([[0.,  0.,  1.],

          [0.,  2.,  0.],

          [3.,  0.,  0.]])

   

   >>> A = np.random.randn(2,3,5)

   >>> np.all(np.fliplr(A) == A[:,::-1,...])

   True

在使用这些函数时,需要确保数组的维度适合进行翻转。

数组的复制

   Examples

   --------

   Create an array x, with a reference y and a copy z:

   

   >>> x = np.array([1, 2, 3])

   >>> y = x

   >>> z = np.copy(x)

   

   Note that, when we modify x, y changes, but not z:

   

   >>> x[0] = 10

   >>> x[0] == y[0]

   True

   >>> x[0] == z[0]

   False

   

   Note that, np.copy clears previously set WRITEABLE=False flag.

   

   >>> a = np.array([1, 2, 3])

   >>> a.flags["WRITEABLE"] = False

   >>> b = np.copy(a)

   >>> b.flags["WRITEABLE"]

   True

   >>> b[0] = 3

   >>> b

   array([3, 2, 3])

   

   Note that np.copy is a shallow copy and will not copy object

   elements within arrays. This is mainly important for arrays

   containing Python objects. The new array will contain the

   same object which may lead to surprises if that object can

   be modified (is mutable):

   

   >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)

   >>> b = np.copy(a)

   >>> b[2][0] = 10

   >>> a

   array([1, 'm', list([10, 3, 4])], dtype=object)

   

   To ensure all elements within an ``object`` array are copied,

   use `copy.deepcopy`:

   

   >>> import copy

   >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)

   >>> c = copy.deepcopy(a)

   >>> c[2][0] = 10

   >>> c

   array([1, 'm', list([10, 3, 4])], dtype=object)

   >>> a

   array([1, 'm', list([2, 3, 4])], dtype=object)

数组的排序

   Examples

   --------

   >>> a = np.array([[1,4],[3,1]])

   >>> np.sort(a)                # sort along the last axis

   array([[1, 4],

          [1, 3]])

   >>> np.sort(a, axis=None)     # sort the flattened array

   array([1, 1, 3, 4])

   >>> np.sort(a, axis=0)        # sort along the first axis

   array([[1, 1],

          [3, 4]])

   

   Use the `order` keyword to specify a field to use when sorting a

   structured array:

   

   >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]

   >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),

   ...           ('Galahad', 1.7, 38)]

   >>> a = np.array(values, dtype=dtype)       # create a structured array

   >>> np.sort(a, order='height')                        # doctest: +SKIP

   array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),

          ('Lancelot', 1.8999999999999999, 38)],

         dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])

   

   Sort by age, then height if ages are equal:

   

   >>> np.sort(a, order=['age', 'height'])               # doctest: +SKIP

   array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),

          ('Arthur', 1.8, 41)],

         dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])


数组的数学操作

加法

>>> added_arr = arr1 + arr2

减法

>>> subtracted_arr = arr1 - arr2

乘法

>>> multiplied_arr = arr1 * arr2

除法

>>> divided_arr = arr1 / arr2

幂运算

>>> power_arr = np.power(arr1, arr2)


数组的统计操作

均值

mean = np.mean(arr)

   Examples

   --------

   >>> a = np.array([[1, 2], [3, 4]])

   >>> np.mean(a)

   2.5

   >>> np.mean(a, axis=0)

   array([2., 3.])

   >>> np.mean(a, axis=1)

   array([1.5, 3.5])

   

   In single precision, `mean` can be inaccurate:

   

   >>> a = np.zeros((2, 512*512), dtype=np.float32)

   >>> a[0, :] = 1.0

   >>> a[1, :] = 0.1

   >>> np.mean(a)

   0.54999924

   

   Computing the mean in float64 is more accurate:

   

   >>> np.mean(a, dtype=np.float64)

   0.55000000074505806 # may vary

   

   Specifying a where argument:

   

   >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])

   >>> np.mean(a)

   12.0

   >>> np.mean(a, where=[[True], [False], [False]])

   9.0

方差

var = np.var(arr)

   Examples

   --------

   >>> a = np.array([[1, 2], [3, 4]])

   >>> np.var(a)

   1.25

   >>> np.var(a, axis=0)

   array([1.,  1.])

   >>> np.var(a, axis=1)

   array([0.25,  0.25])

   

   In single precision, var() can be inaccurate:

   

   >>> a = np.zeros((2, 512*512), dtype=np.float32)

   >>> a[0, :] = 1.0

   >>> a[1, :] = 0.1

   >>> np.var(a)

   0.20250003

   

   Computing the variance in float64 is more accurate:

   

   >>> np.var(a, dtype=np.float64)

   0.20249999932944759 # may vary

   >>> ((1-0.55)**2 + (0.1-0.55)**2)/2

   0.2025

   

   Specifying a where argument:

   

   >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])

   >>> np.var(a)

   6.833333333333333 # may vary

   >>> np.var(a, where=[[True], [True], [False]])

   4.0

标准差

std = np.std(arr)

   Examples

   --------

   >>> a = np.array([[1, 2], [3, 4]])

   >>> np.std(a)

   1.1180339887498949 # may vary

   >>> np.std(a, axis=0)

   array([1.,  1.])

   >>> np.std(a, axis=1)

   array([0.5,  0.5])

   

   In single precision, std() can be inaccurate:

   

   >>> a = np.zeros((2, 512*512), dtype=np.float32)

   >>> a[0, :] = 1.0

   >>> a[1, :] = 0.1

   >>> np.std(a)

   0.45000005

   

   Computing the standard deviation in float64 is more accurate:

   

   >>> np.std(a, dtype=np.float64)

   0.44999999925494177 # may vary

   

   Specifying a where argument:

   

   >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])

   >>> np.std(a)

   2.614064523559687 # may vary

   >>> np.std(a, where=[[True], [True], [False]])

   2.0

最大值、最小值

max_value = np.max(arr)

   Examples

   --------

   >>> a = np.arange(4).reshape((2,2))

   >>> a

   array([[0, 1],

          [2, 3]])

   >>> np.amax(a)           # Maximum of the flattened array

   3

   >>> np.amax(a, axis=0)   # Maxima along the first axis

   array([2, 3])

   >>> np.amax(a, axis=1)   # Maxima along the second axis

   array([1, 3])

   >>> np.amax(a, where=[False, True], initial=-1, axis=0)

   array([-1,  3])

   >>> b = np.arange(5, dtype=float)

   >>> b[2] = np.NaN

   >>> np.amax(b)

   nan

   >>> np.amax(b, where=~np.isnan(b), initial=-1)

   4.0

   >>> np.nanmax(b)

   4.0

   

   You can use an initial value to compute the maximum of an empty slice, or

   to initialize it to a different value:

   

   >>> np.amax([[-50], [10]], axis=-1, initial=0)

   array([ 0, 10])

   

   Notice that the initial value is used as one of the elements for which the

   maximum is determined, unlike for the default argument Python's max

   function, which is only used for empty iterables.

   

   >>> np.amax([5], initial=6)

   6

   >>> max([5], default=6)

   5

min_value = np.min(arr)

   Examples

   --------

   >>> a = np.arange(4).reshape((2,2))

   >>> a

   array([[0, 1],

          [2, 3]])

   >>> np.amin(a)           # Minimum of the flattened array

   0

   >>> np.amin(a, axis=0)   # Minima along the first axis

   array([0, 1])

   >>> np.amin(a, axis=1)   # Minima along the second axis

   array([0, 2])

   >>> np.amin(a, where=[False, True], initial=10, axis=0)

   array([10,  1])

   

   >>> b = np.arange(5, dtype=float)

   >>> b[2] = np.NaN

   >>> np.amin(b)

   nan

   >>> np.amin(b, where=~np.isnan(b), initial=10)

   0.0

   >>> np.nanmin(b)

   0.0

   

   >>> np.amin([[-50], [10]], axis=-1, initial=0)

   array([-50,   0])

   

   Notice that the initial value is used as one of the elements for which the

   minimum is determined, unlike for the default argument Python's max

   function, which is only used for empty iterables.

   

   Notice that this isn't the same as Python's ``default`` argument.

   

   >>> np.amin([6], initial=5)

   5

   >>> min([6], default=5)

   6

PythonTogether

微信公众号

一起来学派森吧

 

显示推荐内容

目录
相关文章
|
7月前
|
存储 Java 数据处理
(numpy)Python做数据处理必备框架!(一):认识numpy;从概念层面开始学习ndarray数组:形状、数组转置、数值范围、矩阵...
Numpy是什么? numpy是Python中科学计算的基础包。 它是一个Python库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种方法,包括数学、逻辑、形状操作、排序、选择、I/0 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。 Numpy能做什么? numpy的部分功能如下: ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++
579 1
|
7月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
363 0
|
9月前
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
857 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
|
9月前
|
存储 数据采集 数据处理
Pandas与NumPy:Python数据处理的双剑合璧
Pandas与NumPy是Python数据科学的核心工具。NumPy以高效的多维数组支持数值计算,适用于大规模矩阵运算;Pandas则提供灵活的DataFrame结构,擅长处理表格型数据与缺失值。二者在性能与功能上各具优势,协同构建现代数据分析的技术基石。
684 0
|
存储 Python
Python 实现单向链表,和单向链表的反转
链表是一种数据结构,每个节点存储相邻节点的位置信息。单链表中的节点仅存储下一节点的位置。通过Python实现单链表,定义`ListNode`类并关联节点可创建链表。例如,创建A-&gt;B-&gt;C的链表后,可通过反转函数`reverse`将链表反转为CBA。代码展示了如何实现和操作单链表。
332 6
Python 实现单向链表,和单向链表的反转
|
存储 Python
Python 中链表的个人理解
简介:本文介绍了Python中链表的基本组成及其操作实现。链表由`head`(头节点)、中间节点和`tail`(尾节点)三部分构成,每个节点通过`Node`类定义,包含`value`(值域)和`next`(指针域)。示例代码展示了链表的增删查功能,包括`add`(头部插入)、`append`(尾部插入)、`remove`(删除节点)、`search`(查找节点)及遍历方法。运行结果验证了链表操作的正确性。
|
存储 算法 搜索推荐
Python 实现反转、合并链表有啥用?
大家好,我是V哥。本文介绍Python实现反转链表和合并链表的应用场景及代码实现。反转链表适用于时间序列数据展示、回文链表判断等;合并链表则用于大规模数据排序、数据库查询结果集合并等。通过迭代和递归方法实现反转链表,以及合并两个或多个有序链表的算法,帮助开发者解决实际问题。关注V哥,了解更多实用编程技巧。 先赞再看后评论,腰缠万贯财进门。
298 0
|
计算机视觉 Python
PIL图像转换为Numpy数组:技术与案例详解
本文介绍了如何将PIL图像转换为Numpy数组,以便利用Numpy进行数学运算和向量化操作。首先简要介绍了PIL和Numpy的基本功能,然后详细说明了转换过程,包括导入库、打开图像文件、使用`np.array()`或`np.asarray()`函数进行转换,并通过打印数组形状验证转换结果。最后,通过裁剪、旋转和缩放等案例展示了转换后的应用,以及如何将Numpy数组转换回PIL图像。此外,还介绍了处理base64编码图像的完整流程。
692 4
|
机器学习/深度学习 数据采集 数据挖掘
解锁 Python 数据分析新境界:Pandas 与 NumPy 高级技巧深度剖析
Pandas 和 NumPy 是 Python 中不可或缺的数据处理和分析工具。本文通过实际案例深入剖析了 Pandas 的数据清洗、NumPy 的数组运算、结合两者进行数据分析和特征工程,以及 Pandas 的时间序列处理功能。这些高级技巧能够帮助我们更高效、准确地处理和分析数据,为决策提供支持。
477 2
|
Python
探索 Python 中链表的实现:从基础到高级
链表是一种由节点组成的基础数据结构,每个节点包含数据和指向下一个节点的引用。本文通过Python类实现单向链表,详细介绍了创建、插入、删除节点等操作,并提供示例代码帮助理解。链表在处理动态数据时具有高效性,适用于大量数据变动的场景。文章为初学者提供了全面的入门指南,助你掌握链表的核心概念与应用。
808 0

热门文章

最新文章

推荐镜像

更多