Python库Numpy学习+代码实例

前言

Numpy是python语言的一个扩充程序库,支持高端大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库,现已成为机器学习的必备模块。
本文章对Numpy库的原文档进行了学习,可作为文档阅读理解来进行阅读。附原文档链接如下:Numpy库文档

库的介绍

该库中的对象为多维数组,原名为ndarray,因此经常被叫做array。python中也有一个库叫做array,但是与这里的ndarray并不相同。前者仅限制在一维上,后者的维数更多且功能更加强大。

基本概念

这里同时给出原文,英语能力比较好的学习者可以直接看原文进行理解。

  • ndarray.ndim
    the number of axes (dimensions) of the array.
    即数组的轴(通俗的理解为维数)
  • ndarray.shape
    the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.
    即数组的形状,以一个元组进行表示,即每个维数的大小。如下方代码中是一个(2, 3)的数组。
[[1, 2, 3, ],
 [4, 5, 6, ]]
  • ndarray.size
    the total number of elements of the array. This is equal to the product of the elements of shape.
    即数组的大小(数组总共包含多少个元素),每个轴的大小乘积。
  • ndarray.dtype
    an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
    描述数组中元素类型的对象。可以使用标准 Python 类型创建或指定 dtypeNumPy 还提供自己的类型。如numpy.int32numpy.int16numpy.float64
  • ndarray.itemsize
    the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
    即数组中每个元素的大小,由于数组中元素均为同一类型,故
  • ndarray.data
    the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.
    包含数组实际元素的缓冲区。通常,我们不需要使用此属性,因为我们将使用索引设施访问数组中的元素。

以上内容比较简单,就不给出代码示例了。

数组的一些函数操作

以下所有操作都在引入库并标名为np的基础上

import numpy as np

数组初始化

全为0或者1
  • np.zeros 函数和np.ones 函数创建指定形状的数组,并分布用0和1填充所有元素。
  • zeros_like函数和ones_like 函数创建和已有数组具有相同形状的数组,并分布用0和1填充所有元素。
a = np.array([1,2,3])
print(a)
# [1 2 3]
a = np.array([3.,2.,4.], dtype = np.int16)
print(a)
# [3 2 4]
a = np.zeros((3,4))
print(a)
# [[0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [0. 0. 0. 0.]]
a = np.ones_like(a)
print(a)
#[[1. 1. 1. 1.]
# [1. 1. 1. 1.]
# [1. 1. 1. 1.]]
等差数组或随机数组
  • np.arange 函数根据下界、上界和步长生成一个由等差数列组成的数组,包括下界但不包括上 界。np.linspace 函数根据下界、上界和数量生成一个由包含指定数量的元素的等差数列组成 的数组,包括下界和上界。
  • numpy库的random模块的seed函数设置随机数种子为10,rand 函数可生成一些服从区间[0,1)内的均匀分布的随机数用以初始化一个指定形状的随机数组。
a = np.arange(2,10,1)
print(a)
# [2 3 4 5 6 7 8 9]
a = np.linspace(1,10,5)
print(a)
# [ 1.    3.25  5.5   7.75 10.  ]
np.random.seed(20); 
a = np.random.rand(3, 2)
print(a)
#[[0.5881308  0.89771373]
# [0.89153073 0.81583748]
# [0.03588959 0.69175758]]
a = np.random.rand(2, 3)
print(a)
#[[0.37868094 0.51851095 0.65795147]
# [0.19385022 0.2723164  0.71860593]]

改变数组形状

改变数组的形状,改变形状是指改变各维度的长度,但不改变组成数组的元素。

  • flatten方法从一个多维数组生成一维数组。
  • reshape方法从原数组生成一个指定形状的新数组。
  • T方法从一个数组h生成它 的转置。以上方法不会改变原数组的形状。
  • resize方法则将原数组改变为指定的形状。
a = np.arange(1, 13).reshape(3, 4)
print(a)
#[[ 1  2  3  4]
# [ 5  6  7  8]
# [ 9 10 11 12]]
a = a.flatten()
print(a)
#[ 1  2  3  4  5  6  7  8  9 10 11 12]
a = a.reshape(2,6)
print(a)
#[[ 1  2  3  4  5  6]
# [ 7  8  9 10 11 12]]
a = a.T
print(a)
#[[ 1  7]
# [ 2  8]
# [ 3  9]
# [ 4 10]
# [ 5 11]
# [ 6 12]]

数组的堆叠

  • np.hstack 函数沿第二个维度将两个数组堆叠在一起形成新的数组。
  • np.vstack函数沿第一个 维度将两个数组堆叠在一起形成新的数组。
  • np.r_函数将多个数组(数值)堆叠在一起形成新的数组,其中语法start:stop:step等同于np.arange(start, stop, step),语法 start:stop:step等同于np.linspace(start, stop, step, endpoint=1)
a = np.arange(1, 7).reshape(2,3)
print(a)
#[[1 2 3]
# [4 5 6]]
b = np.arange(7, 13).reshape(2,3)
print(b)
#[[ 7  8  9]
# [10 11 12]]
c = np.hstack((a, b))
d = np.vstack((a, b))
print(c)
#[[ 1  2  3  7  8  9]
# [ 4  5  6 10 11 12]]
print(d)
#[[ 1  2  3]
# [ 4  5  6]
# [ 7  8  9]
# [10 11 12]]

数组的分割

  • np.hsplit 函数沿第二个维度将一个数组分割成为多个数组,可以指定一个正整数表示均匀分 割得到的数组的数量或指定一个元组表示各分割点的索引值。
  • np.vsplit 函数沿第一个维度将一个数组分割成为多个数组,参数和hsplit类似。
a = np.arange(1, 25).reshape(2, 12)
print(a)
#[[ 1  2  3  4  5  6  7  8  9 10 11 12]
# [13 14 15 16 17 18 19 20 21 22 23 24]]

c = np.hsplit(a,3)
print(c)
#[array([[ 1,  2,  3,  4],
#       [13, 14, 15, 16]]), array([[ 5,  6,  7,  8],
#       [17, 18, 19, 20]]), array([[ 9, 10, 11, 12],
#       [21, 22, 23, 24]])]
d = np.hsplit(a,(4, 7, 9))
print(d)
#[array([[ 1,  2,  3,  4],
#       [13, 14, 15, 16]]), array([[ 5,  6,  7],
#       [17, 18, 19]]), array([[ 8,  9],
#       [20, 21]]), array([[10, 11, 12],
#       [22, 23, 24]])]
b = np.arange(1, 25).reshape(6, 4)
print(b)
#[[ 1  2  3  4]
# [ 5  6  7  8]
# [ 9 10 11 12]
# [13 14 15 16]
# [17 18 19 20]
# [21 22 23 24]]
b = np.vsplit(b, (2, 3, 5))
print(b)
#[array([[1, 2, 3, 4],
#       [5, 6, 7, 8]]), array([[ 9, 10, 11, 12]]), array([[13, 14, 15, 16],
#       [17, 18, 19, 20]]), array([[21, 22, 23, 24]])]

数组的运算

数组的一元运算(取反、乘方)和二元运算(加减乘除)对于每个元素分别进行。两个二维数组之间的矩阵乘法可通过@运算符或dot方法完成。二元运算要求两个数组具有相同的形状。

a = np.arange(6).reshape(2, 3)
print(a)
b = np.arange(2, 18, 3).reshape(2, 3)
print(b)
print(a + b)
print(a - b)
print(a * b)

一维数组可以像列表一样进行索引、切片和迭代。

a = (np.arange(1, 13)**2).reshape(3,4)
print(a)
#[[  1   4   9  16]
# [ 25  36  49  64]
# [ 81 100 121 144]]
b = a[:, 1::2]
print(b)
#[[  4  16]
# [ 36  64]
# [100 144]]
for row in a:
    print(row)
# [ 1  4  9 16]
# [25 36 49 64]
# [ 81 100 121 144]
for row in a:
    for x in row:
        print(x)
#1
#4
#9
#16
#25
#36
#49
#64
#81
#100
#121
#144

数组的复制和视图

在对数组进行运算时,有时元素会复制到一个新数组中,有时不发生复制。

  • view 方法从已有数组创建一个新的数组
def f(x, y): return x * 4 + y + 1
f= np.fromfunction(f, (3, 4), dtype=int)
print(f)
#[[ 1  2  3  4]
# [ 5  6  7  8]
# [ 9 10 11 12]]
k = f
m = f.view()
print(f"{k is f}, {m is f}")
# True, False
print(m)
#[[ 1  2  3  4]
# [ 5  6  7  8]
# [ 9 10 11 12]]
  • NumPy 数组的 flags 属性包含了多个与数组内存布局相关的标志,其中 owndata 用于指示:True为独立分配,False为其他对象共享
print(m.flags.owndata)
# False
m.resize((2, 6))
print(m)
#[[ 1  2  3  4  5  6]
# [ 7  8  9 10 11 12]]
print(m is f)
# False
print(f.shape)
# (3, 4)
print(m[1,3])
# 10
  • copy 方法将已有数组的元素复制到新创建的数组中,新数组和原数组不共享元素。copy 方法的一个用途是复制元素,以后可以用del回收原数组占用的内存空间。
  • ravel方法从一个多维数组生成一个一维数组,也是原数组的一个视图。
a = np.arange(12).reshape(3, 4)
print(a)
#[[ 0  1  2  3]
# [ 4  5  6  7]
# [ 8  9 10 11]]

h = a.copy().reshape(2, 6)
print(h is a)
False
print(h)
#[[ 0  1  2  3  4  5]
# [ 6  7  8  9 10 11]]
a = h.ravel().reshape(4, 3)
print(a)
#[[ 0  1  2]
# [ 3  4  5]
# [ 6  7  8]
# [ 9 10 11]]

得到矩阵中出现过的所有元素以及下标索引

使用np.unique,只设置参数为指定操作数组时,返回矩阵中所有出现过的元素(按第一次出现的顺序)。指定参数为return_index = True时,返回每个元素第一次出现时的索引值。指定参数为return_counts = True时,返回每个元素出现过的次数。

如果是return_index = True时候,返回的索引值是原数组扁平化后的索引值,即数组变为一维数组之后对应的索引值。

np.array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])
unique_values = np.unique(a)
print(unique_values)
# [11 12 13 14 15 16 17 18 19 20]
unique_values, indices_list = np.unique(a, return_index=True)
print(indices_list)
# [ 0  2  3  4  5  6  7 12 13 14]
unique_values, occurrence_count = np.unique(a, return_counts=True)
print(occurrence_count)
# [3 2 2 2 1 1 1 1 1 1]

还有很多复杂的用法,但是基本用不太到,这里就不过多介绍了。

数组的反转

使用方法np.flip()

反转一维数组

直接给出代码,更直观

a = np.array([1,2,3,4,5,6,7,8])
print(a)
# [1 2 3 4 5 6 7 8]
reversed_a = np.flip(a)
print(reversed_a)
# [8 7 6 5 4 3 2 1]
反转二维数组

二维数组的工作方式大致相同。
可以直接反转整个数组,也可以反转行或者反转列,使用参数axis进行确定即可

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

reversed_arr = np.flip(arr_2d)
print(reversed_arr)
#[[12 11 10  9]
# [ 8  7  6  5]
# [ 4  3  2  1]]
reversed_arr_rows = np.flip(arr_2d, axis=0)
print(reversed_arr_rows)
#[[ 9 10 11 12]
# [ 5  6  7  8]
# [ 1  2  3  4]]

reversed_arr_columns = np.flip(arr_2d, axis=1)
print(reversed_arr_columns)
#[[ 4  3  2  1]
# [ 8  7  6  5]
# [12 11 10  9]]

小结

Numpy库的用法还有很多,以上是一些十分基础的内容,建议全部掌握,这样就不需要每次用到的时候都需要去查。Numpy库与机器学习内容息息相关,并且与库matplotlib结合也有很多实用的用法。在之后有时间也会进行总结。

如果以上内容对你有帮助的话,希望可以给博主一个关注点赞和收藏!!!谢谢!!!

你可能感兴趣的:(python,numpy,学习,机器学习)