numpy_example

  |   源代码

介绍numpy/scipy库的基本用法.

In [5]:
import numpy as np
import scipy
In [3]:
# arange 函数, 生成多维数组
a = np.arange(15).reshape(3, 5)
print(a)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
In [20]:
print("每个元素内存大小(单位是byte, int64 是64bit, 64/8=8byte):", a.itemsize)
print("纬度(3行5列,表示为二维数组,所以纬度是2):", a.ndim)
print("元素类型", a.dtype)
print("总元素大小", a.size)
每个元素内存大小(单位是byte, int64 是64bit, 64/8=8byte): 8
纬度(3行5列,表示为二维数组,所以纬度是2): 2
元素类型 int64
总元素大小 15
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))
一维数组: [1 2 3 4] 1
二维数组:  [[1.5 2.  3. ]
 [4.  5.  6. ]] 2
指定数据类型为复数: [[1.+0.j 2.+0.j]
 [3.+0.j 4.+0.j]]
生成值全部是0的数组:  [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
生成值全部是1的数组:  [[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
生成未初始化值的数组:  [[1.5 2.  3. ]
 [4.  5.  6. ]]
生成一定步长的连续数组: [10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
更改数组纬度: [[   0    1    2 ...   97   98   99]
 [ 100  101  102 ...  197  198  199]
 [ 200  201  202 ...  297  298  299]
 ...
 [9700 9701 9702 ... 9797 9798 9799]
 [9800 9801 9802 ... 9897 9898 9899]
 [9900 9901 9902 ... 9997 9998 9999]]
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)
a-b= [20 29 38 47]
a*2= [ 40  60  80 100]
b**2 =  [0 1 4 9]
sin(a) =  [ 0.91294525 -0.98803162  0.74511316 -0.26237485]
cos(a) =  [ 0.40808206  0.15425145 -0.66693806  0.96496603]
a < 35 =  [ True  True False False]
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)
A:  [[0 1]
 [2 3]]
B:  [[4 5]
 [6 7]]
In [2]:
a = np.ones(3, dtype=np.int32)
b = np.linspace(0, np.pi, 3)

print("a+b=", a+b)
a+b= [1.         2.57079633 4.14159265]
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))
a= [[0 1 2]
 [3 4 5]]
a.sum= 15
a.min= 0
a.max= 5
a.sum of each column [3 5 7]
a.sum of each row [ 3 12]
a cumulative sum of cumulative each column [[0 1 2]
 [3 5 7]]
a cumulative sum of cumulative each row [[ 0  1  3]
 [ 3  7 12]]
In [14]:
B = np.arange(3)
print("B=", B)

print("np.exp(B)=", np.exp(B))
print("np.sqrt(B)=", np.sqrt(B))
B= [0 1 2]
np.exp(B)= [1.         2.71828183 7.3890561 ]
np.sqrt(B)= [0.         1.         1.41421356]
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])
a= [  0   1   8  27  64 125 216 343 512 729]
a[2]= 8
a[2:5]= [ 8 27 64]
a after a[:6:2] = -1000:  [-1000     1 -1000    27 -1000   125   216   343   512   729]
a[ : :-1] =  [  729   512   343   216   125 -1000    27 -1000     1 -1000]
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])
通过函数,输入行列坐标,生成二维数组: [[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]
 [40 41 42 43]]
b[2, 3]= 23
b[0:5, 1]= [ 1 11 21 31 41]
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])
c= [[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]
c[1, ...]= [[ 6  7  8]
 [ 9 10 11]]
c[..., 2]= [[ 2  5]
 [ 8 11]]
c.flat= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
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))
a= [[8. 4.]
 [6. 0.]]
b= [[5. 8.]
 [9. 4.]]
np.vstack((a,b)) [[8. 4.]
 [6. 0.]
 [5. 8.]
 [9. 4.]]
np.hstack((a,b)) [[8. 4. 5. 8.]
 [6. 0. 9. 4.]]
np.concatenate((a, b), axis=0)= [[8. 4.]
 [6. 0.]
 [5. 8.]
 [9. 4.]]
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))
np.array_split(a, 4 , axis=1)= [array([[8., 8., 5.],
       [4., 0., 9.],
       [2., 6., 3.],
       [0., 3., 0.]]), array([[3., 3., 1.],
       [3., 9., 2.],
       [6., 4., 4.],
       [9., 3., 8.]]), array([[6., 4., 4.],
       [5., 1., 6.],
       [0., 4., 4.],
       [0., 7., 6.]]), array([[8., 8., 3.],
       [0., 8., 1.],
       [6., 0., 5.],
       [2., 9., 9.]])]
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)
a= [ 0  1  2  3  4  5  6  7  8  9 10 11]
b is a= True
c is a = False
c.base is a = True
c.flags.owndata =  False
d is a = False
d.base is a = True
d.flags.owndata =  False
a= [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
e is a =  False
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)
a= [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
b= [[False False False False]
 [False  True  True  True]
 [ True  True  True  True]]
a[b]= [ 5  6  7  8  9 10 11]
after a[b] = 0, a =  [[0 1 2 3]
 [4 0 0 0]
 [0 0 0 0]]
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()
Comments powered by Disqus