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

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

入门基础(二)

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

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

数组操作

组索引和切片

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

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

数组的整体操作

数组的拼接

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

numpy.concatenate()

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

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

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

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
      [4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
      [2],
      [3],
      [4],
      [5],
      [6]])
numpy.hstack()

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

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

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

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.row_stack((a, b))
array([[1, 2],
       [3, 4],
       [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', '

   

   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', '


数组的数学操作

加法

>>> 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


目录
相关文章
|
2天前
|
Python
全网最适合入门的面向对象编程教程:Python函数方法与接口-函数与方法的区别和lamda匿名函数
【9月更文挑战第15天】在 Python 中,函数与方法有所区别:函数是独立的代码块,可通过函数名直接调用,不依赖特定类或对象;方法则是与类或对象关联的函数,通常在类内部定义并通过对象调用。Lambda 函数是一种简洁的匿名函数定义方式,常用于简单的操作或作为其他函数的参数。根据需求,可选择使用函数、方法或 lambda 函数来实现代码逻辑。
|
2天前
|
存储 机器学习/深度学习 数据挖掘
深入浅出:Python编程入门与实践
【9月更文挑战第16天】本文以“深入浅出”的方式,引领读者步入Python编程的世界。从基础语法到实际应用,我们将一步步探索Python的魅力所在。无论你是编程新手,还是希望拓展技能的老手,这篇文章都将为你提供有价值的信息和指导。通过本文的学习,你将能够编写出简单而实用的Python程序,为进一步深入学习打下坚实的基础。让我们一起开始这段编程之旅吧!
|
2天前
|
机器学习/深度学习 数据挖掘 程序员
Python编程基础:从入门到实践
【9月更文挑战第16天】本文是一篇Python编程的入门教程,旨在帮助初学者理解Python的基本概念和语法。文章首先介绍了Python的历史和特点,然后详细讲解了Python的基本语法,包括变量、数据类型、运算符、控制结构等。接着,文章通过一些实例代码,展示了如何使用Python进行基本的编程操作,如输入输出、条件判断、循环等。最后,文章还提供了一些学习资源和建议,帮助读者进一步学习和掌握Python编程。
|
1天前
|
机器学习/深度学习 数据采集 存储
Python编程入门:从基础到实战
【9月更文挑战第17天】本文将带你进入Python的世界,从最基础的语法开始,逐步深入到实战项目。我们将一起探索Python的强大功能和灵活性,以及如何利用它解决实际问题。无论你是编程新手,还是有一定经验的开发者,都能在这篇文章中找到有价值的内容。让我们一起开启Python的学习之旅吧!
|
2天前
|
存储 程序员 Python
Python编程入门:从零到英雄
【9月更文挑战第16天】本文是一篇针对初学者的Python编程入门指南,旨在帮助读者从零基础开始,通过简单易懂的语言和实例,逐步掌握Python编程的基本知识和技能。文章首先介绍了Python的起源和特点,然后详细讲解了Python的安装、基本语法、数据类型、控制结构、函数、模块等基础知识,最后通过一个简单的项目实例,展示了如何运用所学知识解决实际问题。全文通俗易懂,结构清晰,适合所有对Python感兴趣的读者阅读和学习。
|
28天前
|
机器学习/深度学习 数据处理 计算机视觉
NumPy实践宝典:Python高手教你如何轻松玩转数据处理!
【8月更文挑战第22天】NumPy是Python科学计算的核心库,专长于大型数组与矩阵运算,并提供了丰富的数学函数。首先需安装NumPy (`pip install numpy`)。之后可通过创建数组、索引与切片、执行数学与逻辑运算、变换数组形状及类型、计算统计量和进行矩阵运算等操作来实践学习。NumPy的应用范围广泛,从基础的数据处理到图像处理都能胜任,是数据科学领域的必备工具。
43 0
|
2月前
|
机器学习/深度学习 数据可视化 搜索推荐
Python在社交媒体分析中扮演关键角色,借助Pandas、NumPy、Matplotlib等工具处理、可视化数据及进行机器学习。
【7月更文挑战第5天】Python在社交媒体分析中扮演关键角色,借助Pandas、NumPy、Matplotlib等工具处理、可视化数据及进行机器学习。流程包括数据获取、预处理、探索、模型选择、评估与优化,以及结果可视化。示例展示了用户行为、话题趋势和用户画像分析。Python的丰富生态使得社交媒体洞察变得高效。通过学习和实践,可以提升社交媒体分析能力。
61 1
|
21天前
|
存储 缓存 C语言
|
19天前
|
机器学习/深度学习 存储 算法
NumPy 与 SciPy:Python 科学计算库的比较
【8月更文挑战第30天】
51 1
|
19天前
|
存储 C语言 Python