美文网首页数据分析
[Python] Numpy相关知识

[Python] Numpy相关知识

作者: 半为花间酒 | 来源:发表于2020-05-16 21:24 被阅读0次

内容是以前的学习笔记,内容不全,主观性较大,部分基础知识未展示

1.Numpy基本操作

1.1 列表转为矩阵

import numpy as np
array = np.array([
    [1,3,5],
    [4,6,9]
])

print(array)
[[1 3 5]
 [4 6 9]]

1.2 维度

print('number of dim:', array.ndim)
number of dim: 2

1.3 行数和列数()

print('shape:',array.shape)
shape: (2, 3)

1.4 元素个数

print('size:',array.size)
size: 6

1.5 结构数组

# 结构数组
import numpy as np

persontype = np.dtype({
    'names':['name', 'age', 'chinese', 'math', 'english'],
    'formats':['S32','i', 'i', 'i', 'f']}) # 首先用 dtype 定义结构类型,方式是dict键值对形式,值为list

peoples = np.array([("ZhangFei",32,75,100, 90),("GuanYu",24,85,96,88.5),
       ("ZhaoYun",28,85,92,96.5),("HuangZhong",29,65,85,100)],
    dtype=persontype) # 在定义数组时用 array 中指定了结构数组的类型 dtype=persontype

ages = peoples[:]['age'] # 获取每个人的年龄
chineses = peoples[:]['chinese']
maths = peoples[:]['math']
englishs = peoples[:]['english']

print(ages)
print (np.mean(ages)) # 计算平均值的函数 np.mean()

1.6 获得说明文档

numpy.info(numpy.add)

1.7 获取时间

yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')

# 获取一个月的所有日期
Z = np.arange('2020-02', '2020-03', dtype='datetime64[D]')
print(Z)

1.8 提取浮点数的整数部分

Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))

2.Numpy创建array

2.1 一维array创建

import numpy as np
# 一维array
a = np.array([2,23,4], dtype=np.int32) # np.int默认为int32
print(a)
print(a.dtype)
[ 2 23  4]
int32

2.2 多维array创建

# 多维array
a = np.array([[2,3,4],
              [3,4,5]])
print(a) # 生成2行3列的矩阵
[[2 3 4]
 [3 4 5]]

2.3 创建全零数组

a = np.zeros((3,4))
print(a) # 生成3行4列的全零矩阵, np.zeros()
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

2.4 创建全1数据

# 创建全一数据,同时指定数据类型
a = np.ones((3,4),dtype=np.int) # 可以不再具体指定np.int32或np.int64
print(a)
[[1 1 1 1]
 [1 1 1 1]
 [1 1 1 1]]

2.5 创建全空数组

# 创建全空数组,其实每个值都是接近于零的数,实际不是空
a = np.empty((3,4))
print(a)
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

2.6 创建连续数组

# 创建连续数组,一维
a = np.arange(10,21,2) # 10-20的数据,步长为2,类似内置函数range()
print(a)
[10 12 14 16 18 20]

2.7 reshape操作

# 使用reshape改变上述数据的形状
b = a.reshape((2,3))  # reshape()里需放tuple指明行列,小括号内带有小括号
print(b)

array = np.array([
    [1,3,5],
    [4,6,9]])
b = array.reshape((3,2))
print(b)
[[10 12 14]
 [16 18 20]]
 
 [[1, 3],
  [5, 4],
  [6, 9]]

2.8 创建连续型数据

# 创建线段型数据
a = np.linspace(1,10,20) # 开始端1,结束端10,且分割成20个数据,生成线段
print(a)
[ 1.          1.47368421  1.94736842  2.42105263  2.89473684  3.36842105
  3.84210526  4.31578947  4.78947368  5.26315789  5.73684211  6.21052632
  6.68421053  7.15789474  7.63157895  8.10526316  8.57894737  9.05263158
  9.52631579 10.        ]

2.9 linspace的reshape操作

# 同时也可以reshape
b = a.reshape((5,4))
print(b)
[[ 1.          1.47368421  1.94736842  2.42105263]
 [ 2.89473684  3.36842105  3.84210526  4.31578947]
 [ 4.78947368  5.26315789  5.73684211  6.21052632]
 [ 6.68421053  7.15789474  7.63157895  8.10526316]
 [ 8.57894737  9.05263158  9.52631579 10.        ]]

2.10 矩阵的内存大小

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
Z.itemsize=8 # 返回内存大小
Z.size=100

2.11 创建单位矩阵

Z = np.eye(3)
print(Z)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

2.12 创建随机数数组

Z = np.random.random((3,3,3))
print(Z)
[[[0.80803306 0.15598703 0.34893017]
  [0.42996238 0.65370225 0.29571015]
  [0.98431042 0.60065601 0.69715523]]

 [[0.0401535  0.48688523 0.66349519]
  [0.36911515 0.15464677 0.34794222]
  [0.03057509 0.16662922 0.13865098]]

 [[0.88234883 0.80486331 0.34130986]
  [0.72021469 0.2606817  0.67648494]
  [0.37799242 0.79685409 0.43181634]]]

2.13 二维数组添加边界

Z = np.ones((5,5))
Z = np.pad(Z, pad_width=2, mode='constant', constant_values=0)
print(Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0. 0.]
 [0. 0. 1. 1. 1. 1. 1. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]

2.14 二维数组添加对角线

Z = np.diag(1+np.arange(4),k=-1) # k参数表示移动
print(Z)
[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]

2.15 二维数组棋盘

Z = np.zeros((8,8),dtype=np.int64)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)

# 也可以用 np.tile()
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

2.16 返回多维数组指定位置的索引

print(np.unravel_index(100,(6,7,8)))

2.17 寻找两个一维数组的交集

# intersect1d
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))

3.Numpy基本运算

3.1 一维矩阵运算

import numpy as np
# 一维矩阵运算
a = np.array([10,20,30,40])
b = np.arange(4)
print(a,b)
[10 20 30 40] [0 1 2 3]
c = a - b
print(c)
[10 19 28 37]
print(a*b) 
print(a.dot(b)) # 各维之和
[  0  20  60 120]

200
# 在Numpy中,想要求出矩阵中各个元素的乘方需要依赖双星符号 **,以二次方举例,即:
c = b**2
print(c)
[0 1 4 9]
# Numpy中具有很多的数学函数工具
c = np.sin(a)
print(c)
[-0.54402111  0.91294525 -0.98803162  0.74511316]
print(b<2)
[ True  True False False]
a = np.array([1,1,4,3])
b = np.arange(4)
print(a==b)
[False  True False  True]

3.2 多维矩阵运算

a = np.array([[1,1],[0,1]])
b = np.arange(4).reshape((2,2))
print(a)
print(b)
[[1 1]
 [0 1]]

[[0 1]
 [2 3]]
# 多维度矩阵乘法
# 第一种乘法方式:
c = a.dot(b)
print(c)
[[2 4]
 [2 3]]
# 第二种乘法:
c = np.dot(a,b)
print(c)
# 多维矩阵乘法不能直接使用'*'号
[[2 4]
 [2 3]]
a = np.random.random((2,4))  # random取值(0,1),构建2行4列

print(np.sum(a)) 
print(np.min(a)) # 或 a.min()
print(np.max(a))  # 或 a.max()
3.825517216750851

0.09623355767721398

0.7420428188342583
print("a=",a)
a= [[0.48634962 0.74204282 0.09623356 0.69074812]
 [0.60218881 0.52734181 0.41434585 0.26626662]]

如果你需要对行或者列进行查找运算,

就需要在上述代码中为 axis 进行赋值。

当axis的值为0的时候,将会以列作为查找单元,

当axis的值为1的时候,将会以行作为查找单元。

print("sum=",np.sum(a,axis=1)) # 行 跨列 列索引
print("min=",np.min(a,axis=0)) # 列 跨行 行索引
print("max=",np.max(a,axis=1))
sum= [2.01537412 1.8101431 ]

min= [0.48634962 0.52734181 0.09623356 0.26626662]

max= [0.74204282 0.60218881]

归一化

(x - min) / (max - min)

Z = np.random.random((5,5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)

3.3 基本计算

import numpy as np

A = np.arange(2,14).reshape((3,4))
print(A)
[[ 2  3  4  5]
 [ 6  7  8  9]
 [10 11 12 13]]
# 数组的简单运算
x1 = np.arange(1,11,2)
x2 = np.linspace(1,9,5)

print (np.add(x1, x2)) # 加
print (np.subtract(x1, x2)) # 减
print (np.multiply(x1, x2)) # 乘
print (np.divide(x1, x2)) # 除

print (np.power(x1, x2)) # 乘方,x1为底,x2为指数
print (np.remainder(x1, x2)) # 取余,等同于 np.mod(x1, x2)
[ 2.  6. 10. 14. 18.]
[0. 0. 0. 0. 0.]
[ 1.  9. 25. 49. 81.]
[1. 1. 1. 1. 1.]

[1.00000000e+00 2.70000000e+01 3.12500000e+03 8.23543000e+05
 3.87420489e+08]
[0. 0. 0. 0. 0.]
# 最小元素索引
print(np.argmin(A)) # 0
# 最大元素索引
print(np.argmax(A)) # 11

# 求整个矩阵的均值
print(np.mean(A)) # 7.5
print(np.average(A)) # 7.5
print(A.mean()) # 7.5

# 中位数
print(A.median()) # 7.5
0
11

7.5
7.5
7.5

7.5
# 累加,注意和sum()的区别
print(np.cumsum(A))
[ 2  5  9 14 20 27 35 44 54 65 77 90]
# 求间差运算(各行 后数-前数)
B = np.array([[3,5,9],
              [4,8,10]])
print(np.diff(B))
[[2 4]
 [4 2]]
# 计数组 / 矩阵中的最大值函数 amax(),最小值函数 amin()

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

print (np.amin(a))
print (np.amin(a,axis=0)) # amin(a,0) 是延着 axis=0 轴(跨行 纵向)的各数组元素最小值
print (np.amin(a,axis=1)) # amin(a,1) 是延着 axis=1 轴(跨列 横向)的各数组元素最小值
1
[1 2 3]
[1 4 7]
# 统计最大值与最小值之差 ptp()

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

print (np.ptp(a))
print (np.ptp(a,0)) 
print (np.ptp(a,1)) 
8
[6 6 6]
[2 2 2]
# 统计数组的百分位数 percentile()

a = np.array([[1,2,3], [4,5,6], [7,8,9]])

print (np.percentile(a, 50)) #  p=100 就是求最大值
print (np.percentile(a, 50, axis=0))
print (np.percentile(a, 50, axis=1))
5.0
[4. 5. 6.]
[2. 5. 8.]
# 统计数组中的加权平均值 average()

a = np.array([1,2,3,4])
wts = np.array([1,2,3,4]) # 设置权重

print (np.average(a)) # 权重相等,此时等于 np.mean(a)
print (np.average(a,weights=wts))
2.5
3.0
# 统计数组中的标准差 std()、方差 var()

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

print (np.std(a)) # 标准差
print (np.var(a)) # 方差
1.118033988749895
1.25
C = np.array([[0,5,9],
              [4,0,10]])
print(np.nonzero(B))  # 返回数组a中非零元素的索引值数组,只有非零元素才会有索引值
print(np.nonzero(C))

# 按总索引的顺序读,先按axis=0返回,再按照axis=1返回所有
(array([0, 0, 0, 1, 1, 1], dtype=int64), array([0, 1, 2, 0, 1, 2], dtype=int64))
(array([0, 0, 1, 1], dtype=int64), array([1, 2, 0, 2], dtype=int64))
# 仿照列表排序
A = np.arange(14,2,-1).reshape((3,4)) # -1表示反向递减一个步长
print(A)
print(np.sort(A)) # 默认按照axis=1升序排序
[[14 13 12 11]
 [10  9  8  7]
 [ 6  5  4  3]]

[[11 12 13 14]
 [ 7  8  9 10]
 [ 3  4  5  6]]

NumPy 排序

sort 函数: sort(a, axis=-1, kind=‘quicksort’, order=None)默认为升序

  1. kind: 可以指定 quicksort、mergesort、heapsort 分别表示快速排序、合并排序、堆排序
  2. axis: 默认是 -1,即沿着数组的最后一个轴进行排序; axis=None 代表采用扁平化的方式作为一个向量进行排序
  3. order: 对于结构化的数组可以指定按照某个字段进行排序
降序排列:
Numpy:(np.sort(A,order='total')[::-1])
Pandas:df.sort_values(by='total',ascending=False)
内置函数:np.array(sorted(A,reverse = True))
# 矩阵转置
print(np.transpose(A)) 
print(A.T) # 等同 np.transpose(A)
print(A)
[[14 10  6]
 [13  9  5]
 [12  8  4]
 [11  7  3]]
 
 [[14 13 12 11]
 [10  9  8  7]
 [ 6  5  4  3]]
print(np.clip(A,5,9))
[[9 9 9 9]
 [9 9 8 7]
 [6 5 5 5]]

clip(Array,Array_min,Array_max)

将Array_min<X<Array_max X表示矩阵A中的数,如果满足上述关系,则原数不变。

否则,如果X<Array_min,则将矩阵中X变为Array_min;

如果X>Array_max,则将矩阵中X变为Array_max.

4.Numpy索引与切片

import numpy as np
A = np.arange(3,15)
print(A)
print(A[3])
[ 3  4  5  6  7  8  9 10 11 12 13 14]
6
B = A.reshape(3,4)
print(B)
print(B[2])  # 二维矩阵的索引为行索引

print(B[0][2])
print(B[0,2]) # 矩阵[行,列] 二者相同
[[ 3  4  5  6]
 [ 7  8  9 10]
 [11 12 13 14]]
 
 [11 12 13 14]
 
 5
# list切片操作
print(B[1,1:3]) # [8 9] 1:3表示1-2不包含3
[8 9]
for row in B:
    print(row)
[3 4 5 6]
[ 7  8  9 10]
[11 12 13 14]
# 如果要打印列,则进行转置即可
for column in B.T:
    print(column)
[ 3  7 11]
[ 4  8 12]
[ 5  9 13]
[ 6 10 14]
# 多维转一维
A = np.arange(3,15).reshape((3,4))
# print(A)
print(A.flatten())
# flat是一个迭代器,本身是一个object属性
[ 3  4  5  6  7  8  9 10 11 12 13 14]
for item in A.flat:  # A.flatten()和A.flat作用相同
    print(item)
3
4
5
6
7
8
9
10
11
12
13
14

5.Numpy array合并

5.1 数组合并

import numpy as np
A = np.array([1,1,1]) # 列表转成一维数组
B = np.array([2,2,2])
print(np.vstack((A,B)))
# vertical stack 上下合并,对括号的两个整体操作。
[[1 1 1]
 [2 2 2]]
C = np.vstack((A,B))  # 多维矩阵列数相同则可以用np.vstack()
print(C)
[[1 1 1]
 [2 2 2]]
print(A.shape,B.shape,C.shape)# 从shape中看出A,B均为拥有3项的数组(数列)
(3,) (3,) (2, 3) 
# horizontal stack左右合并
D = np.hstack((A,B))  # 多维矩阵行数相同则可以用np.vstack()
print(D)
[1 1 1 2 2 2]
print(A.shape,B.shape,D.shape)
# (3,) (3,) (6,)
# 对于A,B这种,为数组或数列,无法进行转置,需要借助其他函数进行转置
(3,) (3,) (6,)  # 一维数组的np.shape为(np.size,)
               # 一维横向矩阵的np.shape为(1,np.size)
                # 一维纵向矩阵的np.shape为(np.size,1)
                # A = np.array(lst)为一维数组
                # B = A[np.newaxis,:]为一维横向矩阵
                # C = A[:,np.newaxis]为一维横向矩阵

5.2 数组转置为矩阵

print(A[np.newaxis,:]) # [1 1 1]变为[[1 1 1]]
[[1 1 1]]
print(A[np.newaxis,:].shape) # (3,)变为(1, 3)
(1, 3)
print(A[:,np.newaxis])
[[1]
 [1]
 [1]]

5.3 多个矩阵合并

# concatenate的第一个例子
print("------------")
print(A[:,np.newaxis].shape) # (3,1)
------------
(3, 1)
A = A[:,np.newaxis] # 数组转为矩阵
B = B[:,np.newaxis] # 数组转为矩阵
print(A)
[[1]
 [1]
 [1]]
print(B)
[[2]
 [2]
 [2]]
# axis=0纵向合并 多个矩阵 纵向合并要求列数相同
C = np.concatenate((A,B,B,A),axis=0) # 两个矩阵等同 C = np.hstack((A,B))
print(C)
[[1]
 [1]
 [1]
 [2]
 [2]
 [2]
 [2]
 [2]
 [2]
 [1]
 [1]
 [1]]
# axis=1横向合并 多个矩阵 横向合并要求行数相同
C = np.concatenate((A,B),axis=1) # 两个矩阵等同 C = np.vstack((A,B))
print(C)
[[1 2]
 [1 2]
 [1 2]]

5.4 合并例子2

# concatenate的第二个例子
print("-------------")
a = np.arange(8).reshape(2,4)
b = np.arange(8).reshape(2,4)
print(a)
print(b)
print("-------------")
-------------
[[0 1 2 3]
 [4 5 6 7]]
[[0 1 2 3]
 [4 5 6 7]]
-------------
# axis=0多个矩阵纵向合并
c = np.concatenate((a,b),axis=0)
print(c)
[[0 1 2 3]
 [4 5 6 7]
 [0 1 2 3]
 [4 5 6 7]]
# axis=1多个矩阵横向合并
c = np.concatenate((a,b),axis=1)
print(c)
[[0 1 2 3 0 1 2 3]
 [4 5 6 7 4 5 6 7]]

6.Numpy array分割

6.1 构造3行4列矩阵

import numpy as np
A = np.arange(12).reshape((3,4))
print(A)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

6.2 等量分割

# 等量分割
# 纵向分割同横向合并的axis
print(np.split(A, 2, axis=1)) # 横向分割指定数量,需是倍数
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]
# 横向分割同纵向合并的axis
print(np.split(A,3,axis=0))
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]

6.3 不等量分割

print(np.array_split(A,3,axis=1))
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2],
       [ 6],
       [10]]), array([[ 3],
       [ 7],
       [11]])]

6.4 其他的分割方式

# 横向分割
print(np.vsplit(A,3)) # 等价于print(np.split(A,3,axis=0))
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]
# 纵向分割
print(np.hsplit(A,2)) # 等价于print(np.split(A,2,axis=1))
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]

7.Numpy copy与 =

7.1 =赋值方式会带有关联性

import numpy as np
# `=`赋值方式会带有关联性,很重要,对a的修改会影响b
a = np.arange(4)
print(a) # [0 1 2 3]
[0 1 2 3]
b = a
c = a
d = b
a[0] = 11
print(a) # [11  1  2  3]
[11  1  2  3]
print(b) # [11  1  2  3]
[11  1  2  3]
print(c) # [11  1  2  3]
[11  1  2  3]
print(d) # [11  1  2  3]
[11  1  2  3]
print(b is a) # True
True
print(c is a) # True
True
print(d is a) # True
True
d[1:3] = [22,33] # 前闭后开
print(a) # [11 22 33  3]
[11 22 33  3]
print(b) # [11 22 33  3]
[11 22 33  3]
print(c) # [11 22 33  3]
[11 22 33  3]

7.2 copy()赋值方式没有关联性

a = np.arange(4)
print(a) # [0 1 2 3]
[0 1 2 3]
b =a.copy() # deep copy
print(b) # [0 1 2 3]
[0 1 2 3]
a[3] = 44
print(a) # [ 0  1  2 44]
print(b) # [0 1 2 3]

# 此时a与b已经没有关联
[ 0  1  2 44]
[0 1 2 3]

8.广播机制

numpy数组间的基础运算是一对一,也就是a.shape==b.shape,但是当两者不一样的时候,就会自动触发广播机制,如下例子:

from numpy import array
a = array([[ 0, 0, 0],
           [10,10,10],
           [20,20,20],
           [30,30,30]])
b = array([0,1,2])
print(a+b)
[[ 0  1  2]
 [10 11 12]
 [20 21 22]
 [30 31 32]]

为什么是这个样子?

这里以tile模拟上述操作,来回到a.shape==b.shape情况!

# 对[0,1,2]行重复3次,列重复1次
b = np.tile([0,1,2],(4,1))
print(a+b)
[[ 0  1  2]
 [10 11 12]
 [20 21 22]
 [30 31 32]]

当然不是,只有当两个数组的trailing dimensions compatible时才会触发广播,否则报错ValueError: frames are not aligned exception

上面表达意思是尾部维度必须兼容!

9.常用函数

9.1 np.bincount()

x = np.array([1, 2, 3, 3, 0, 1, 4])
np.bincount(x)
array([1, 2, 1, 2, 1], dtype=int64)

统计索引出现次数:索引0出现1次,1出现2次,2出现1次,3出现2次,4出现1次

因此通过bincount计算出索引出现次数如下:

上面怎么得到的?

对于bincount计算吗,bin的数量比x中最大数多1,例如x最大为4,那么bin数量为5(index从0到4),也就会bincount输出的一维数组为5个数,bincount中的数又代表什么?代表的是它的索引值在x中出现的次数!

还是以上述x为例子,当我们设置weights参数时候,结果又是什么?

这里假定:

w = np.array([0.3,0.5,0.7,0.6,0.1,-0.9,1])

那么设置这个w权重后,结果为多少?

np.bincount(x,weights=w)
array([ 0.1, -0.6,  0.5,  1.3,  1. ])

怎么计算的?

先对x与w抽取出来:

x ---> [1, 2, 3, 3, 0, 1, 4]

w ---> [0.3,0.5,0.7,0.6,0.1,-0.9,1]
索引 0 出现在x中index=4位置,那么在w中访问index=4的位置即可,w[4]=0.1

索引 1 出现在x中index=0与index=5位置,那么在w中访问index=0index=5的位置即可,然后将两这个加和,计算得:w[0]+w[5]=-0.6
其余的按照上面的方法即可!

bincount的另外一个参数为minlength,这个参数简单,可以这么理解,当所给的bin数量多于实际从x中得到的bin数量后,后面没有访问到的设置为0即可。

还是上述x为例:

这里我们直接设置minlength=7参数,并输出!

np.bincount(x,weights=w,minlength=7)
array([ 0.1, -0.6,  0.5,  1.3,  1. ,  0. ,  0. ])

与上面相比多了两个0,这两个怎么会多?

上面知道,这个bin数量为5,index从0到4,那么当minlength为7的时候,也就是总长为7,index从0到6,多了后面两位,直接补位为0即可!

9.2 np.argmax()

函数原型为:numpy.argmax(a, axis=None, out=None).

函数表示返回沿轴axis最大值的索引。

x = [[1,3,3],
     [7,5,2]]
print(np.argmax(x))
3

对于这个例子我们知道,7最大,索引位置为3(这个索引按照递增顺序)!

axis属性

axis=0表示按列操作,也就是对比当前列,找出最大值的索引!

x = [[1,3,3],
     [7,5,2]]
print(np.argmax(x,axis=0))
[1 1 0]

axis=1表示按行操作,也就是对比当前行,找出最大值的索引!

x = [[1,3,3],
     [7,5,2]]
print(np.argmax(x,axis=0))
[1 1 0]

那如果碰到重复最大元素?

返回第一个最大值索引即可!

例如:

x = np.array([1, 3, 2, 3, 0, 1, 0])
print(x.argmax())
1

9.3 上述合并实例

这里来融合上述两个函数,举个例子:

x = np.array([1, 2, 3, 3, 0, 1, 4])
print(np.argmax(np.bincount(x)))
1

最终结果为1,为什么?

首先通过np.bincount(x)得到的结果是:[1 2 1 2 1],再根据最后的遇到重复最大值项,则返回第一个最大值的index即可!2的index为1,所以返回1。

9.4 求取精度

np.around([-0.6,1.2798,2.357,9.67,13], decimals=0)#取指定位置的精度
array([-1.,  1.,  2., 10., 13.])

看到没,负数进位取绝对值大的!

np.around([1.2798,2.357,9.67,13], decimals=1) # 会四舍五入
array([ 1.3,  2.4,  9.7, 13. ])
np.around([1.2798,2.357,9.67,13], decimals=2)
array([ 1.28,  2.36,  9.67, 13.  ])

从上面可以看出,decimals表示指定保留有效数的位数,当超过5就会进位(此时包含5)!

但是,如果这个参数设置为负数,又表示什么?

np.around([1,2,5,6,56], decimals=-1)
array([ 0,  0,  0, 10, 60])

发现没,当超过5时候(不包含5),才会进位!-1表示看一位数进位即可,那么如果改为-2呢,那就得看两位!

np.around([1,2,5,50,56,190], decimals=-2)
array([  0,   0,   0,   0, 100, 200])

看到没,必须看两位,超过50才会进位,190的话,就看后面两位,后两位90超过50,进位,那么为200!

计算沿指定轴第N维的离散差值

x = np.arange(1 , 16).reshape((3 , 5))
print(x)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]]
np.diff(x,axis=1) #默认axis=1
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
np.diff(x,axis=0)  # 后数-前数
array([[5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5]])

取整

np.floor([-0.6,-1.4,-0.1,-1.8,0,1.4,1.7]) # 向下取整
array([-1., -2., -1., -2.,  0.,  1.,  1.])

看到没,负数取整,跟上述的around一样,是向左!

取上限

np.ceil([1.2,1.5,1.8,2.1,2.0,-0.5,-0.6,-0.3])
array([ 2.,  2.,  2.,  3.,  2., -0., -0., -0.]) # 向上取整

取上限!找这个小数的最大整数即可!

查找

利用np.where实现小于0的值用0填充吗,大于0的数不变!

x = np.array([[1, 0],
       [2, -2],
     [-2, 1]])
print(x)
[[ 1  0]
 [ 2 -2]
 [-2  1]]
# 查找满足和不满足的存在,只是替换
np.where(x>0,x,0)
array([[1, 0],
       [2, 0],
       [0, 1]])
# 查找,不满足的剔除
a = np.array([[4,3,2],[2,4,1]])
np.extract(a>2,a) 
array([4, 3, 4])

相关文章

网友评论

    本文标题:[Python] Numpy相关知识

    本文链接:https://www.haomeiwen.com/subject/wufdohtx.html