numpy_example
介绍numpy/scipy库的基本用法.
In [5]:
import numpy as np
import scipy
In [3]:
# arange 函数, 生成多维数组
a = np.arange(15).reshape(3, 5)
print(a)
In [20]:
print("每个元素内存大小(单位是byte, int64 是64bit, 64/8=8byte):", a.itemsize)
print("纬度(3行5列,表示为二维数组,所以纬度是2):", a.ndim)
print("元素类型", a.dtype)
print("总元素大小", a.size)
In [37]:
# 可以直接使用python 本身的list创建数组
a = np.array([1, 2, 3, 4])
print("一维数组:", a, a.ndim)
b = np.array([(1.5,2,3), (4,5,6)])
print("二维数组: ", b, b.ndim)
# 指定数据类型
c = np.array( [ [1,2], [3,4] ], dtype=complex )
print("指定数据类型为复数:", c)
# 还有一些快速生成一定规则数组的方法
print("生成值全部是0的数组: ", np.zeros((3, 4)))
print("生成值全部是1的数组: ", np.ones((3, 4)))
print("生成未初始化值的数组: ", np.empty((2, 3)))
print("生成一定步长的连续数组:", np.arange(10, 100, 5))
print( "更改数组纬度:", np.arange(10000).reshape(100,100))
In [3]:
# 加减运算
a = np.array( [20,30,40,50] )
b = np.arange(4)
print("a-b=", a-b)
print("a*2=", a*2)
print("b**2 = ", b**2)
print("sin(a) = ", np.sin(a))
print("cos(a) = ", np.cos(a))
print("a < 35 = ", a<35)
In [50]:
A = np.arange(0, 4, 1).reshape(2, 2)
B = np.arange(4, 8, 1).reshape(2, 2)
print("A: ", A)
print("B: ", B)
In [2]:
a = np.ones(3, dtype=np.int32)
b = np.linspace(0, np.pi, 3)
print("a+b=", a+b)
In [11]:
a = np.arange(6).reshape(2,3)
print("a=", a)
print("a.sum=", a.sum())
print("a.min=", a.min())
print("a.max=", a.max())
print("a.sum of each column", a.sum(axis=0))
print("a.sum of each row", a.sum(axis=1))
print("a cumulative sum of cumulative each column", a.cumsum(axis=0))
print("a cumulative sum of cumulative each row", a.cumsum(axis=1))
In [14]:
B = np.arange(3)
print("B=", B)
print("np.exp(B)=", np.exp(B))
print("np.sqrt(B)=", np.sqrt(B))
In [21]:
a = np.arange(10)**3
print("a=", a)
print("a[2]=", a[2])
print("a[2:5]=", a[2:5])
a[:6:2] = -1000
print("a after a[:6:2] = -1000: ", a)
print("a[ : :-1] = ", a[ : :-1])
In [27]:
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)
print("通过函数,输入行列坐标,生成二维数组:", b)
print("b[2, 3]=", b[2, 3])
print("b[0:5, 1]=", b[0:5, 1])
In [35]:
c = np.arange(12).reshape((2, 2,3))
print("c=",c)
print('c[1, ...]=', c[1,...])
print('c[..., 2]=', c[...,2])
print('c.flat=', [e for e in c.flat])
In [45]:
# 多维数组栈/拼接操作
a = np.floor(10* np.random.random((2, 2)))
b = np.floor(10* np.random.random((2, 2)))
print("a=", a)
print("b=", b)
print("np.vstack((a,b))", np.vstack((a,b)))
print("np.hstack((a,b))", np.hstack((a,b)))
print("np.concatenate((a, b), axis=0)=", np.concatenate((a, b), axis=0))
In [49]:
# spliting
a = np.floor(10*np.random.random((4,12)))
print("np.array_split(a, 4 , axis=1)=", np.array_split(a, 4 , axis=1))
In [64]:
# array copy
a= np.arange(12)
print("a=", a)
b = a
b.shape = 3, 4
print("b is a=", b is a)
c = a.view()
print("c is a =", c is a)
print("c.base is a =", c.base is a)
print("c.flags.owndata = ", c.flags.owndata)
d = a[:, 1:3]
print("d is a =", d is a)
print("d.base is a =", d.base is a)
print("d.flags.owndata = ", d.flags.owndata)
print("a=", a)
e = a.copy()
print("e is a = ", e is a)
In [67]:
# fancy indexing and index tricks
a = np.arange(12).reshape(3,4)
b = a > 4
print("a=", a)
print("b=", b)
print("a[b]=", a[b])
a[b] = 0
print("after a[b] = 0, a = ", a)
In [101]:
# 利用boolean类型的索引生成 Mandelbrot(曼德勃罗图像)
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
"""Returns an image of the Mandelbrot fractal of size (h,w)."""
y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
c = x+y*1j
z=c
# print(id(z), id(c))
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z**2 + c
diverge = z*np.conj(z) > 2**2 # who is diverging
div_now = diverge & (divtime==maxit) # who is diverging now
divtime[div_now] = i
z[diverge] = 2
return divtime
plt.imshow(mandelbrot(800,800, 20))
plt.show()
In [105]:
import matplotlib.pyplot as plt
rng = np.random.RandomState(10) # deterministic random data
#print(rng.normal(size=1000))
a = np.hstack((rng.normal(size=1000), rng.normal(loc=5, scale=2, size=1000)))
plt.hist(a, bins='auto') # arguments are passed to np.histogram
plt.title("Histogram with 'auto' bins")
plt.show()