前菜--Numpy

import numpy as np

NumPy : numberial python

NumPy的核心:数据结构 ndarray

1.1 数组方法

np.array 创建数组 基本语法:np.array([[],[],[]……[]])

# 生成1 维数组
a = np.array([1,2,3,4])
a
array([1, 2, 3, 4])
#生成二维数组
a = np.array([
    [1,2,3,4],
    [5,6,7,8],
    [7,7,7,7]
])
a
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [7, 7, 7, 7]])

我们还可以使用np.arange(start,stop,step,dtype)生成等差数组

·start 表示开始数字 为下确界 默认为0
·stop 表示结束的数 为上界
·step 表示公差 默认为1
·dtype 指定数据类型 默认inter32
因为start、step和dtype都有默认值,所以可以只写入stop

#下面创建一个从0到9的数组
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#创建首项为1 截止到10(不包含) 指定步长2
np.arange(1,10,2)
array([1, 3, 5, 7, 9])

np.linspace(start,stop,num,endpoint)使得我们可以不必计算公差来生成一个等差数组

·num 该等差数组的个数
·endpoint 序列中是否包含stop值,注意这里默认为true
explain:这个方法主要是我们知道首尾之后使用的,所以endpoint默认为true

#比如我们只知道一个数组首项为0,最后一项为10,且该数组有5个数
np.linspace(0,10,5)
array([ 0. ,  2.5,  5. ,  7.5, 10. ])

np.reshape 改变数组的形状

#将一个一维数组转为二维
np.arange(10).reshape(2,5)
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

有一些比较特殊的数组我们可以numpy提供了一键生成的方法

#都是1的数组可以使用np.ones来生成 参数为矩阵的形状
#可以用np.ones_like(a)来生成和a形状一样的数组
#默认为1维
np.ones(10) # 生成一维十个分量都为一的数组
np.ones((2,5)) #生成二维每个维度的五个等量都为一的数组

array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

同理,可以生成所需的全为零(zeros),没有初始化(empty),特定数(full)的数组

使用random随机函数创建数组

#创建五个范围在[0,1)之间的数据
#这里需要说明:random函数生成的范围为左闭右开
np.random.rand(5)
array([0.44632437, 0.81121282, 0.80482189, 0.41552902, 0.92565849])
#指定shape
np.random.rand(3,4)
array([[0.38044668, 0.18780878, 0.88673987, 0.5911139 ],
       [0.93546119, 0.64607342, 0.62441079, 0.74648861],
       [0.5757769 , 0.16007626, 0.55954991, 0.55501118]])
#randint(low,high,(shape))生成随机整数 区间[low,high)
#low默认为0
np.random.randint(1,10,(3,4))
array([[9, 7, 8, 9],
       [5, 9, 5, 1],
       [3, 7, 9, 6]])
#uniform()生成在[low,high)之间均匀分布的数字
np.random.uniform(1,10,(3,4))
array([[6.03188774, 3.39992438, 3.56467481, 2.58653308],
       [2.85072574, 2.46446551, 6.80989601, 1.84529343],
       [2.98288733, 7.39698989, 7.89446111, 7.4762518 ]])
#randn()生成的数据具有标准正态分布 均值为0,方差为1
np.random.randn(3,4)
array([[ 0.82166166,  0.44499244, -1.82220382, -0.04496252],
       [ 0.31283332, -1.4152152 ,  1.12381001,  1.88690788],
       [-0.121892  , -0.48383337, -0.19617823, -2.80674969]])
#normal() 可以指定均值和标准差
np.random.normal(5,10,(3,4))
array([[14.78332891, 23.10401466, -2.25248365,  6.21926006],
       [ 8.4929957 ,  3.29216256, -3.71472177,  1.58433458],
       [-4.55193955,  3.40607897, -9.00472229,  6.96018844]])
#choice(给定数组,结果的shape) 从给定的数组中,产生随机结果
np.random.choice(5,(2,3))
#等同于 np.random.choice(0,5,3)
array([[3, 4, 1],
       [0, 4, 2]])
#shuffle 把一个数组的分量随机排列
(array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]),
 array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]))

1.2 数组属性:

#生成二维数组
a = np.array([
    [1,2,3,4],
    [5,6,7,8],
    [7,7,7,7]
])
a
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [7, 7, 7, 7]])
# ndim 返回一个数组的维度
a.ndim
2
#shape 返回一个元组 array的维度和每个维度有几个分量
#系数矩阵的形状
a.shape
(3, 4)
#dtype array中元素的数据类型
a.dtype
dtype('int32')
#size 返回一个array中所有元素的加总值
a.size
12
#itemsize 返回数组中每个元素的大小
a.itemsize
4

1.3 数组索引 大致和原生List相同

基础索引

#首先创建一个数组
x = np.arange(10)
#取出x中的第一个元素的值
#注意:缩影是从0开始的
x[0]
0
# 取值2-8
# 数组的数也是从0开始的,所以2的索引为2
# 又因为8靠近数组的上界,所以索引可以用-2
# 但是当我们使用区间来表示索引的时候 区间的范围是左闭右开
x[2:-1]
array([2, 3, 4, 5, 6, 7, 8])
#再生成一个多维数组
y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
y.ndim
2
#取第二行第一列的数据
#行列的索引也是从0开始
y[0,0]
0
#取所有第二行的元素
y[1]
array([5, 6, 7, 8, 9])
#取所有第二列的元素
y[:,1]
array([ 1,  6, 11, 16])
x[:2] = 666 #修改数表中的元素是索引最大的作用
x
array([666, 666,   2,   3,   4,   5,   6,   7,   8,   9])
y[1,0] = 1
y
array([[ 0,  1,  2,  3,  4],
       [ 1,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

切片 basic slicing

需要注意的是:基础切片产生的是view,而修改view会对原来的数组产生影响

可以使用以下方法来切片
slice object (constructed by start:stop:step notation inside of brackets)(等差数列) i:j:k
an integer
a tuple of slice objects and integers.
Ellipsis and newaxis objects can be interspersed with these as well.(维度索引)

维度索引工具

There are some tools to facilitate the easy matching of array shapes with expressions and in assignments.

Ellipsis

expands to the number of : objects needed for the selection tuple to index all dimensions.
所以 ... 把 : 拓展到了所有维度的index上,

x = np.array([
    [[1],[2],[3]], 
    [[4],[5],[6]]
])
x[...,0]
array([[1, 2, 3],
       [4, 5, 6]])
x[:,:,0]
array([[1, 2, 3],
       [4, 5, 6]])

newaxis

expand the dimensions of the resulting selection by one unit-length dimension.The added dimension is the position of the newaxis object in the selection tuple.
newaxis = None
new一个axis,添加一个维度.

x[:, np.newaxis, :, :].shape # 原来是2,3,1 现在添加了一个维度
(2, 1, 3, 1)
x[:, None, :, :].shape # 功能相同
(2, 1, 3, 1)

This can be handy to combine two arrays in a way that otherwise would require explicit reshaping operations. For example:

x = np.arange(5)
a = x[:,np.newaxis]
b = x[np.newaxis,:]
# x[:,np.newaxis] + x[np.newaxis,:]
a , b
(array([[0],
        [1],
        [2],
        [3],
        [4]]),
 array([[0, 1, 2, 3, 4]]))
a + b
array([[0, 1, 2, 3, 4],
       [1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])

索引进阶:整数索引,布尔索引

整数索引

学习之前,我们先来看看官方文档上的一个tip

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).
返回的是一个副本,在副本上操作不会改变原来的array

copy和view辨析

The definition of advanced indexing means that x[(1, 2, 3),] is fundamentally different than x[(1, 2, 3)]. The latter is equivalent to x[1, 2, 3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.

Also recognize that x[[1, 2, 3]] will trigger advanced indexing, whereas due to the deprecated Numeric compatibility mentioned above, x[[1, 2, slice(None)]] will trigger basic slicing.
Thus, x[ind1, ..., ind2,:] acts like x[ind1][..., ind2, :] under basic slicing.This not true for advanced indexing.

x = np.arange(64).reshape(4,4,4) # 三维数组
a = x[(1,2,3),]#在最高维度上的index是1,2,3
b = x[(1,2,3)]#在第三维度上的index是1,第二维度上的index是2,第一维度上的index是3
c = x[[1,2,3]]
d = x[1][2][3],
#d = x[[1,2,slice(None)]]#弃用了的数字兼容性
x,a,b,c,d
(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],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],
 
        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],
 
        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 array([[[16, 17, 18, 19],
         [20, 21, 22, 23],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],
 
        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],
 
        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 27,
 array([[[16, 17, 18, 19],
         [20, 21, 22, 23],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],
 
        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],
 
        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 27)
x = np.arange(10)
indexs = np.array([
    [0,2],
    [1,3]
])
x[indexs]
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

二维数组中的使用方法
y[[r_1,r_2,……,r_n],[c_1,c_2,……,c_n]]
r_i为第i个元素的行,c_i为第i个元素的列

y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
y[[0,2],[0,1]]
array([ 0, 11])

布尔索引

x = np.arange(10)
x > 6
x[ x > 6]#返回x>6为真时索引对应的元素
array([7, 8, 9])

谈到布尔我们就不得不谈一下布尔运算符号 & |

x = np.arange(10)
condition = (x%2 == 0) | (x > 7)
x[condition]
array([0, 2, 4, 6, 8, 9])

1.4数组运算

#基础运算和矩阵是一致的
#但是两个数组的乘法是单纯的对应相乘
# 2*3的矩阵和3*2的矩阵运算
a = np.arange(6,12).reshape(2,3)
b = np.random.randint(2,10,(2,3))
a,b
(array([[ 6,  7,  8],
        [ 9, 10, 11]]),
 array([[2, 8, 6],
        [8, 7, 9]]))
a * b
array([[12, 56, 48],
       [72, 70, 99]])

1.4.1预置函数

#sum求和函数
#prod乘积
#cumsum累加
#cumprod累乘
#min最小值
#max最大值
#quantile 获取四分位的数值
#median中位数
#mean平均数
#std标准差
#var方差
#average(数据,权值)加权平均

1.5 axis参数

axis = 0 表示行,axis = 1 表示列
对于sum/mean/media等聚合函数

  • axis = 0 表示把行消解掉 跨行运算
  • axis = 1 表示把列消解掉,跨列运算

1.6 添加维度

1.6.1 上文讲到的newaxis

1.6.2 np.expand_dims

np.expand_dims(arr,axis = 0|1)

1.6.3 np.reshape

1.7 数组合并

1.7.1合并行

a = np.arange(6).reshape(2,3)
b = np.arange(6,18).reshape(4,3)

我们发现a,b列数相同

np.concatenate([a,b])
np.vstack([a,b])
np.row_stack([a,b])

1.7.2合并列

a = np.arange(12).reshape(3,4)
b = np.arange(12,18).reshape(3,2)

我们发现a,b行数相同

np.concatenate([a,b],axis=1)
np.hstack([a,b])
np.column_stack([a,b])
posted @ 2023-01-05 12:52  epictus  阅读(88)  评论(0编辑  收藏  举报