numpy相关使用


相关学习资料 : numpy中文网

https://www.numpy.org.cn/



1    

numpy索引区间为左闭右开,第一个索引能取到,第二个索引取不到

索引内可加步长

import numpy  as np

a=np.arange(10)

print(a,a[:3],a[::3])


结果为

[0 1 2 3 4 5 6 7 8 9] [0 1 2] [0 3 6 9]


2

使用 ones zeros 构造向量或者矩阵时,注意有两个括号,

如   c1=np.ones((3,4))   函数输入参数为元组


3

numpy索引中括号内可加条件

如 a[a%2==0] 


4

numpy运算效率比python循环快很多,默认的加减乘除全部为标量计算。

np.dot(a,b) 为计算 a与b的内积


5

numpy 自动会把返回结果变成行向量。

reshape可以解决这个问题。如

c=np.arange(5).reshape(5)


6

all,any函数的区别

import numpy as np

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

b=np.array([1,2,3,0])

c=a==b

print(c)

print((a==b).all(),(a==b).any())

结果为

[ True  True  True False]
False True


7

axis参数

import numpy as np

a=np.random.randint(-5,5,(3,3))

print(a)

b1=a.sum(axis=0)

b2=a.sum(axis=1)

b=a.sum(axis=0).sum()

print(b1,b2,b)

结果为

[[-5 -1 -5]
  [ 3  2 -4]
  [ 4  2 -2]]
[  2   3 -11] [-11   1   4] -6

——————————————————

常用功能

import numpy  as np

a=np.arange(0,51,10).reshape(6,1) + np.arange(6)

print(a)

结果为

[[ 0  1  2  3  4  5]
[10 11 12 13 14 15]
  [20 21 22 23 24 25]
  [30 31 32 33 34 35]
  [40 41 42 43 44 45]
  [50 51 52 53 54 55]]


a=np.arange(5)   ‘生成内容为0,1,2,3,4的行向量


b=np.linspace(0,2,5) #生成[0,2]区间等分5的行向量

print(b)

c1=np.ones((3,4))

c2=np.zeros((3,4))

c3=np.eye(3)

c4=np.random.randn(3,3)

print(c1,c2,c3,c4)


[0.  0.5 1.  1.5 2. ]  #对应b
[[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]  #全1矩阵3x4

[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]] #全0矩阵3x4

[[1. 0. 0.]
  [0. 1. 0.]
  [0. 0. 1.]]  #3阶单位矩阵

[[-0.54285003 -0.87924659  0.68505122]
  [ 1.0115468   2.20624087  0.52882636]
  [-1.33261978 -0.51162084  0.22503309]] #随机数组

————————————————————

生成随机整数型矩阵

import numpy as np

a=np.random.random_integers(-5,5,(3,3))

print(a)


结果


[[ 1 -1  3]
  [-3  0 -5]
  [ 0  2  3]]


DeprecationWarning: This function is deprecated. Please call randint(-5, 5 + 1) instead
   a=np.random.random_integers(-5,5,(3,3))

这句是说用 randint代替random_integers

import numpy as np

a=np.random.randint(-5, 5 ,(3,3))

print(a)


——————————————————

内置数学函数

cos exp sqrt

sum mean min max argmin argmax函数


import numpy as np

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

print(a)

print(np.cos(a),np.sin(a),np.exp(a),np.sqrt(a))

print(a.sum(),a.mean(),a.std(),a.min(),a.max())

print(a.argmin(),a.argmax())


[1 2 3 4]  #a
[ 0.54030231 -0.41614684 -0.9899925  -0.65364362]   #cos

[ 0.84147098  0.90929743  0.14112001 -0.7568025 ]   #sin

[ 2.71828183  7.3890561  20.08553692 54.59815003]   #exp

[1.         1.41421356 1.73205081 2.        ]  #sqrt
10 2.5 1.118033988749895 1 4   #加和 均值 方差 最小值 最大值
0 3  #最小值 和 最大值的索引

原文地址:https://www.cnblogs.com/XUEYEYU/p/11907098.html