# Python之Numpy初识

Numpy相比TensorFlow的环境搭建要容易多了，校验的方式也很简单，import即可。

>>> import numpy

>>> numpy.version.full_version

'1.13.3'

>>>

>>> import numpy as np

>>> np.version.full_version

'1.13.3'

>>> a = np.arange(10)

>>> print a

[0 1 2 3 4 5 6 7 8 9]

>>> type(a)

<type 'numpy.ndarray'>

>>> a = a.reshape(2,5)

>>> print a

[[0 1 2 3 4]

[5 6 7 8 9]]

>>> a = np.arange(20)

>>> a = a.reshape(4,5)

>>> print a

[[ 0 1 2 3 4]

[ 5 6 7 8 9]

[10 11 12 13 14]

[15 16 17 18 19]]

>>> a = a.reshape(2,2,5)

>>> print a

[[[ 0 1 2 3 4]

[ 5 6 7 8 9]]

[[10 11 12 13 14]

[15 16 17 18 19]]]

>>>

>>> a = a.reshape(2,2,6)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: cannot reshape array of size 20 into shape (2,2,6)

>>>

>>> a.ndim

3

>>> a.shape

(2L, 2L, 5L)

>>> a.size

20

>>> raw = [0,1,2,3,4]

>>> a = np.array(raw)

>>> a

array([0, 1, 2, 3, 4])

>>> print a

[0 1 2 3 4]

>>> raw = [[0,1,2,3,4],[5,6,7,8,9]]

>>> b = np.array(raw）

>>> b

array([[0, 1, 2, 3, 4],

[5, 6, 7, 8, 9]])

>>>

>>> d = (4,5)

>>> np.zeros(d)

array([[ 0., 0., 0., 0., 0.],

[ 0., 0., 0., 0., 0.],

[ 0., 0., 0., 0., 0.],

[ 0., 0., 0., 0., 0.]])

>>> np.ones(d,dtype=int)

array([[1, 1, 1, 1, 1],

[1, 1, 1, 1, 1],

[1, 1, 1, 1, 1],

[1, 1, 1, 1, 1]])

>>> np.random.rand(5)

array([ 0.61643689, 0.15915655, 0.20558268, 0.75157157, 0.50395262])

>>> a = np.array([[1,2],[2,5]])

>>> print a

[[1 2]

[2 5]]

>>> b = np.array([[2,3],[5,8]])

>>> print a+b

[[ 3 5]

[ 7 13]]

>>> a = np.arange(20).reshape(4,5)

>>> print a

[[ 0 1 2 3 4]

[ 5 6 7 8 9]

[10 11 12 13 14]

[15 16 17 18 19]]

>>> print str(a.sum())

190

>>> print str(a.max())

19

>>> print str(a.min())

0

>>> print str(a.max(axis=1))

[ 4 9 14 19]

>>>

>>> b = np.arange(2,45,3).reshape(5,3)

>>> b = np.mat(b)

>>> print b

[[ 2 5 8]

[11 14 17]

[20 23 26]

[29 32 35]

[38 41 44]]

>>> np.linspace(0,2,5)

array([ 0. , 0.5, 1. , 1.5, 2. ])

>>> np.linspace(0,2,9)

array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])

>>>

>>> a = np.array([[3,2],[5,9]])

>>> print a[0][1]

2

>>> print a[1][0]

5

>>> print a[1,0]

5

>>> b = a

>>> a[0][1]=100

>>> print a

[[ 3 100]

[ 5 9]]

>>> print b

[[ 3 100]

[ 5 9]]

>>> a = np.array([[3,2],[5,9]])

>>> b = a.copy()

>>> a[0][1] = 100

>>> print a

[[ 3 100]

[ 5 9]]

>>> print b

[[3 2]

[5 9]]

>>> a = np.arange(20).reshape(4,5)

>>> print a

[[ 0 1 2 3 4]

[ 5 6 7 8 9]

[10 11 12 13 14]

[15 16 17 18 19]]

>>> print a[:,[1,3]]

[[ 1 3]

[ 6 8]

[11 13]

[16 18]]

>>> a = np.array((1,2,3))

>>> b = np.array((2,3,4))

>>> print np.column_stack((a,b))

[[1 2]

[2 3]

[3 4]]

• 博文量
1498
• 访问量
14471744