数组定义
In [1] : np.array([2, 3, 6, 7])
Out[l] : array([2, 3, 6, 7])
In [2]:np.arange(10,100,20,dtype = float)
Out[2]:array([10.,30.,50.,70.,90.])
linspace(start,stop,num)返回数字间隔均匀的样本,按区间[start,stop]计算
In [3]:np.linspace(0.,2.5,5)
Out[3]:array([0.,0.625,1.25,1.875,2.5])
In [4]:np.zeros((3,)) #等于np.zeros(3),全0填充
Out[4]:array([0., 0., 0.])
In [5]: np.zeros((1,3))
Out[5]: array([[0., 0., 0.]])
In [6] : np.zeros((2, 2), complex)
Out[6] : array([[ 0.+0.j, 0.+0.j],
[ 0.+O.j, 0.+0.j]])
In [7]: np.ones((2, 3)) # ones(),全1填充数组
Out[7]: array([[ 1., 1., 1.],
[ 1., 1., 1.]])
In [1] : np.random.rand(2, 4)
Out[1] : array([[ 0.373767 , 0.24377115, 0.1050342 , 0.16582644] ,
[ 0.31149806, 0.02596055, 0.42367316, 0.67975249l])
randn: 均值为0,标准差为1的标准(高斯)正态分布
In [2]: np.random.randn(2, 4)
Out[2]: array([[ O.87747152, 0.39977447, -0.83964985, -1.05129899],
[-1.07933484, 0.49448873, -1.32648606, -0.94193424]])
操作数组
- 改变数组维度
In [4]:a=np.arange(12)
In [5]: print(a)
Out[4]:array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
In [6]: a.shape = (3,4) #等于a.reshape((3,4))
Out[5]: array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [30] : a = np.arange(5); a
Out[30] : array([0, 1, 2, 3, 4])
In [31] : b = a[2:]; b
Out[31] : array([2, 3, 4])
In [32] : b[0] = 100
In [33] : b
Out[33] : array([l00, 3, 4])
In [34] : a
Out[34] : array([0,1,100,3,4])
In [1]: a = np,linspace(0. 1, 12); a,shape ' (3, 4); a
Out[1]:array([[ O. , 0.09090909, 0.18181818, 0.27272727],
[ 0.36363636, 0.45454545, 0.54545455, 0.63636364],
[ 0.72727273, 0.81818182. 0.90909091, 1.]])
In [2]: np.savetxt("myfile.txt", a)
save()将表保存为Numpy“.npy”格式的二进制文件 (save() saves a table to a binary file in NumPy “.npy” format.)
In [3] : np.save("myfile" ,a)
生成一个二进制文件myfile .npy,其中包含一个可以使用np.load()加载的文件。
- 将文本文件读入数组
loadtxt()将以文本文件存储的表读入数组。
默认情况下,loadtxt()假定列是用空格分隔的。 可以通过修改可选的参数进行更改。 以散列(#)开头的行将被忽略。
示例文本文件data.txt:
|Year| Min temp.| Hax temp.|
|1990| -1.5 | 25.3|
|1991| -3.2| 21.2|
In [1] : tabla = np.loadtxt("data.txt")
In [2] : table
Out[2] : array ([[ 1.99000000e+03, -1.50000000e+00, 2.53000000e+01],
[ 1.9910000e+03, -3.2000000e+00, 2.12000000e+01]