点击下载程序中用到的文件
from numpy import *
#使用 numpy.array 来创建数组
v = array([1,2,3,4])
print(v)
m = array([[1,2],[3,4]])
print(m)
#v 与 m 对象都是 numpy 模块提供的 ndarray 类型
print(type(v))
print(type(m))
#通过 ndarray.shape 获得它的维度属性
print(v.shape)
print(shape(m))
print(m.shape)
#数组的元素数量可以通过 ndarray.size 得到
print(m.size)
print(size(m))
#使用 ndarray 的 dtype 属性我们能获得数组元素的类型
print(m.dtype)
#使用数组生成函数
print(arange(0,10,1))
print(arange(-1,1,0.1))
print(linspace(0,10,25))
print(logspace(0,10,10,base=e))
x,y = mgrid[0:5,0:5]
print(x)
print(y)
print(random.rand(5,5))
print(random.randn(5,5))
print(diag([1,2,3],k=1))
print(zeros((3,3)))
print(ones((3,3)))
#使用 numpy.savetxt 我们可以将 Numpy 数组保存到csv文件中:
M = random.rand(3,3)
savetxt("random-matrix.csv", M, fmt='%.5f')
#使用 numpy.save 与 numpy.load 保存和读取:
save("random-matrix.npy", M)
load("random-matrix.npy")
#文件 I/O 创建数组
import matplotlib.pyplot as plt
data = genfromtxt('stockholm_td_adj.dat')
print(data.shape)
fig ,ax1 = plt.subplots(figsize=(14,4))
ax1.plot(data[:,0]+data[:,1]/12.0+data[:,2]/365, data[:,5])
ax1.axis('tight')
plt.title('temperatures in Stockholm')
plt.xlabel('year')
plt.ylabel('temperature(c)')
plt.show()
#numpy 数组的常用属性
s1 = array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
#数组中每个元素的字节大小
print(s1.itemsize)
#number of bytes
print(s1.nbytes)
# number of dimensions
print(m.ndim)
#操作数组
#索引
print(s1[0])
print(s1[1,1])
# row 1
print(s1[1,:])
# colum 1
print(s1[:,1])
#利用索引进行赋值:
s1[0,0] = 123
print(s1)
s1[1,:] = 0
print(s1)
#切片索引
#切片索引语法:A[lower:upper:step]
A = array([1,2,3,4,5,6])
print(A[1:3])
#进行切片赋值时,原数组会被修改:
A[1:3] = [-2,-3]
print(A)
#可以省略 M[lower:upper:step] 中的任意参数:
print(A[::])# lower, upper, step all take the default values
print(A[::2])# step is 2, lower and upper defaults to the beginning and end of the array
print(A[:3])# first three elements
print(A[3:])# elements from index 3
#负值索引从数组尾开始计算:
print(A[-1])
print(A[-3:])# the last three elements
#索引切片在多维数组的应用也是一样的:
B=array([[n+m*10 for n in range(5)] for m in range(5)])
print(B)
print(B[1:4,1:4])
print(B[::2,::2])
#高级索引:使用列表或者数组进行索引
haha=[1,2,3]
print(B[haha])
dada=[1,2,-1]
print(B[haha,dada])
C = array([n for n in range(5)])
ddd = array([True,False,True,False,False])
print(C[ddd])
ccc = array([1,0,1,0,0],dtype=bool)
print(C[ccc])
xx = arange(0,10,0.5)
mask = (5<xx)*(xx<7.5)
print(mask)
print(xx[mask])
#操作 numpy 数组的常用函数
#where 函数能将索引掩码转换成索引位置
indices = where(mask)
print(indices)
print(xx[indices])
#使用 diag 函数能够提取出数组的对角线
print(diag(B))
#take 函数与高级索引(fancy indexing)用法相似
v2=arange(-3,3)
rooo=[1,3,5]
print(v2[rooo])
print(v2.take(rooo))
#choose选取多个数组的部分组成新的数组
which=[1,0,1,0]
ch = [[-2,-1,0,1],[5,6,7,8]]
print(choose(which,ch))
from numpy import *
A = array([[n+m*10 for n in range(5)] for m in range(5)])
v1 = arange(0,5)
#print(A)
#print(v1)
#标量运算
#print(v1*2)
#print(v1+2)
#print(A*2)
#print(A+2)
#Element-wise(逐项乘) 数组-数组 运算
#print(A*A)
#print(v1*v1)
#print(A.shape)
#print(v1.shape)
#print(A*v1)
#矩阵代数
#矩阵乘法要怎么办? 有两种方法。
#1.使用 dot 函数进行 矩阵-矩阵,矩阵-向量,数量积乘法
#print(dot(A,A))
#print(dot(A,v1))
#print(dot(v1,v1))
#2.将数组对象映射到 matrix 类型
M=matrix(A)
v=matrix(v1).T# make it a column vector
#print(v)
#print(M*M)
#print(M*v)
#print(v.T*v)
#print(v+M*v)
#数组/矩阵 变换
C = matrix([[1j,2j],[3j,4j]])
print(C)
#print(conjugate(C))#共轭
#print(C.H)#共轭转置
#real 与 imag 能够分别得到复数的实部与虚部:
#print(real(C))
#print(imag(C))
#angle 与 abs 可以分别得到幅角和绝对值
#print(angle(C+1))
#print(abs(C))
#矩阵计算
#矩阵求逆
from scipy.linalg import *
print(inv(C))# equivalent to C.I
#行列式
print(linalg.det(C))
print(linalg.det(C.I))
from numpy import *
import matplotlib.pyplot as plt
data = genfromtxt('stockholm_td_adj.dat')
#print(data.shape)
#平均值
# the temperature data is in column 3
#print(mean(data[:,3]))
#标准差 与 方差
#print(std(data[:,3]))
#print(var(data[:,3]))
#最小值 与 最大值
#print(data[:,3].min())
#print(data[:,3].max())
#总和, 总乘积 与 对角线和
d = arange(0, 10)
#print(d)
#print(sum(d))# sum up all elements
# product of all elements
#print(prod(d+1))
# cummulative sum
#print(cumsum(d))
# cummulative product
#print(cumprod(d+1))
#对子数组的操作
#print(unique(data[:,1]))
mm = data[:,1] == 2
#print(mm)
#print(mean(data[mm,3]))
#作图
months = arange(1,13)
monthly_mean = [mean(data[data[:,1] == month,3]) for month in months]
plt.bar(months,monthly_mean)
plt.xlabel("Month")
plt.ylabel("Monthly avg. temp.")
#plt.show()
#对高维数组的操作
m = random.rand(3,3)
#print(m.max())# global max
# max in each column
#print(m.max(axis=0))
# max in each row
#print(m.max(axis=1))
#改变形状与大小
A = array([[n+m*10 for n in range(5)] for m in range(5)])
#print(A)
l,s = A.shape
B = A.reshape((1,l*s))
#print(B)
B[0,0:5] = 5 # modify the array
#print(B)
#print(A)# and the original variable is also changed. B is only a different view of the same data
#我们也可以使用 flatten 函数创建一个高阶数组的向量版本,但是它会将数据做一份拷贝。
C = A.flatten()
#print(C)
C[0:5] = 10
#print(C)
#print(A)# now A has not changed, because B's data is a copy of A's, not refering to the same data
#newaxis 可以帮助我们为数组增加一个新维度,比如说,将一个向量转换成列矩阵和行矩阵:
v = array([1,2,3])
#print(shape(v))
#print(v[:,newaxis])# make a column matrix of the vector v
# column matrix
#print(v[:,newaxis].shape)
# row matrix
#print(v[newaxis,:])
#函数 repeat, tile, vstack, hstack, 与 concatenate能帮助我们以已有的矩阵为基础创建规模更大的矩阵。
a = array([[1, 2], [3, 4]])
# repeat each element 3 times
#print(repeat(a, 3))
# tile the matrix 3 times
#print(tile(a, 3))
b = array([[5, 6]])
#print(concatenate((a, b), axis=0))
#print(concatenate((a, b.T), axis=1))
#print(vstack((a,b)))
#print(hstack((a,b.T)))
#为了获得高性能,Python 中的赋值常常不拷贝底层对象,这被称作浅拷贝。
x = array([[1,2],[3,4]])
#print(x)
y = x
y[0,0] = 10
#print(y)
#print(x)
#如果我们希望避免改变原数组数据的这种情况,那么我们需要使用 copy 函数进行深拷贝:
z = copy(x)
z[0,0] = -5
#print(z)
#print(x)
# 遍历数组元素
o = array([1,2,3,4])
for element in o:
print(element)
p = array([[1,2], [3,4]])
for row in p:
print("row", row)
for element in row:
print(element)
#当我们需要遍历数组并且更改元素内容的时候,可以使用 enumerate 函数同时获取元素与对应的序号:
for row_idx, row in enumerate(p):
print("row_idx", row_idx, "row", row)
for col_idx, element in enumerate(row):
print("col_idx", col_idx, "element", element)
# update the matrix M: square each element
p[row_idx, col_idx] = element ** 2
print(p)
#矢量化函数
#为了获得更好的性能我们最好尽可能避免遍历我们的向量和矩阵,有时可以用矢量算法代替。首先要做的就是将标量算法转换为矢量算法:
def Theta(x):
if x >= 0:
return 1
else:
return 0
#为了得到 Theta 函数的矢量化版本我们可以使用 vectorize 函数
Theta_vec = vectorize(Theta)
print(Theta_vec(array([-3,-2,-1,0,1,2,3])))
#数组与条件判断
k = array([[1,4],[9,16]])
if (k > 5).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")
if (k > 5).all():
print("all elements in M are larger than 5")
else:
print("not all elements in M are larger than 5")
#类型转换
#既然 Numpy 数组是静态类型,数组一旦生成类型就无法改变。但是我们可以显示地对某些元素数据类型进行转换生成新的数组,使用 astype 函数
print(k.dtype)
k2 = k.astype(float)
print(k2.dtype)
k3 = k.astype(bool)
print(k3.dtype)
网友评论