本文介绍一些numpy的基础运算
Demo.py
#对一维数组进行操作
import numpy as np
a=np.array([10,20,30,40]) # array([10, 20, 30, 40])
b=np.arange(4) # array([0, 1, 2, 3])
c=a-b # array([10, 19, 28, 37])
print c
c=a+b # array([10, 21, 32, 43])
print c
c=a*b # array([ 0, 20, 60, 120])
print c
c=b**2 # array([0, 1, 4, 9])
print c
c=10*np.sin(a)
print c
print b<3
# array([ True, True, True, False], dtype=bool)
#对多维数组进行操作
#关于 sum(), min(), max()的使用
import numpy as np
a=np.random.random((2,4))
#对a的操作是令a中生成一个2行4列的矩阵,且每一元素均是来自从0到1的随机数
#print a
# array([[ 0.94692159, 0.20821798, 0.35339414, 0.2805278 ],
# [ 0.04836775, 0.04023552, 0.44091941, 0.21665268]])
print np.sum(a) # 4.4043622002745959
print np.min(a) # 0.23651223533671784
print np.max(a) # 0.90438450240606416
#如果你需要对行或者列进行查找运算,就需要在上述代码中为 axis 进行赋值。
print "a =",a
# a = [[ 0.23651224 0.41900661 0.84869417 0.46456022]
# [ 0.60771087 0.9043845 0.36603285 0.55746074]]
print "sum =",np.sum(a,axis=1)#当axis的值为1的时候,将会以行作为查找单元。
# sum = [ 1.96877324 2.43558896]
print "min =",np.min(a,axis=0)#当axis的值为0的时候,将会以列作为查找单元
# min = [ 0.23651224 0.41900661 0.36603285 0.46456022]
print "max =",np.max(a,axis=1)
# max = [ 0.84869417 0.9043845 ]
结果:
[10 19 28 37]
[10 21 32 43]
[ 0 20 60 120]
[0 1 4 9]
[-5.44021111 9.12945251 -9.88031624 7.4511316 ]
[ True True True False]
[[1 1]
[0 1]]
[[0 1]
[2 3]]
[[2 4]
[2 3]]
[[2 4]
[2 3]]
4.86697754129
0.392121318071
0.95110386776
a = [[ 0.57126351 0.95110387 0.73275929 0.39212132]
[ 0.64227461 0.5118515 0.40201937 0.66358408]]
sum = [ 2.64724798 2.21972956]
min = [ 0.57126351 0.5118515 0.40201937 0.39212132]
max = [ 0.95110387 0.66358408]