TVP

# Python之Numpy初识

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

>>> import numpy

'1.13.3'

>>> import numpy as np

'1.13.3'

>>> a = np.arange(10)

>>> print a

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

>>> type(a)

>>> 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 "", line 1, in

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)

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）

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]])

>>> 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())

>>> 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

>>> 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]]

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180106B004CV00?refer=cp_1026
• 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 cloudcommunity@tencent.com 删除。

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2023-02-08

2019-11-22

10元无门槛代金券