您的位置:首页 > 编程语言 > Python开发

Python Numpy学习笔记

2017-05-08 23:31 429 查看

Python Numpy学习笔记

1. 数据类型



2. 创建矩阵

>>>np.zeros((2, 3))
array([[ 0., 0., 0.], [ 0., 0., 0.]])

>>>np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>>np.arange(2, 10, dtype=np.float)
array([ 2., 3., 4., 5., 6., 7., 8., 9.])

>>>np.arange(2, 3, 0.1)
array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])

>>> np.linspace(1., 4., 6)
array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])

>>> np.indices((3,3))
array([[[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]])


3. 索引

>>> x = np.arange(10)
>>> x[2]
2
>>> x[-2]
8
>>> x.shape = (2,5) # now x is 2-dimensional
>>> x[1,3]
8
>>> x[1,-1]
9
>>> x[0]
array([0, 1, 2, 3, 4])
>>> x[0][2]
2
>>> x = np.arange(10)
>>> x[2:5]
array([2, 3, 4])
>>> x[:-7]
array([0, 1, 2])
>>> x[1:7:2]
array([1, 3, 5])
>>> y = np.arange(35).reshape(5,7)
>>> y[1:5:2,::3]
array([[ 7, 10, 13],
[21, 24, 27]])
>>> x = np.arange(10,1,-1)
>>> x
array([10, 9, 8, 7, 6, 5, 4, 3, 2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])
>>> x[np.array([3,3,-3,8])]
array([7, 7, 4, 2])
>>> x[np.array([3, 3, 20, 8])]
<type ’exceptions.IndexError’>: index 20 out of bounds 0<=index<9
>>> x[np.array([[1,1],[2,3]])]
array([[9, 9],
[8, 7]])
>>> y[np.array([0,2,4]), np.array([0,1,2])]
array([ 0, 15, 30])
>>> y[np.array([0,2,4]), np.array([0,1])]
<type ’exceptions.ValueError’>: shape mismatch: objects cannot be
broadcast to a single shape
>>> y[np.array([0,2,4]), 1]
array([ 1, 15, 29])
>>> y[np.array([0,2,4])]
array([[ 0, 1, 2, 3, 4, 5, 6],
[14, 15, 16, 17, 18, 19, 20],
[28, 29, 30, 31, 32, 33, 34]])
>>> b = y>20
>>> y
array([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34])
>>> b[:,5] # use a 1-D boolean whose first dim agrees with the first dim of y
array([False, False, False, True, True], dtype=bool)
>>> y[b[:,5]]
array([[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34]])
>>> x = np.arange(30).reshape(2,3,5)
>>> x
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])
>>> b = np.array([[True, True, False], [False, True, True]])
>>> x[b]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])


[b]4. 矩阵局部赋值


>>> x = np.arange(10)
>>> x[2:7] = 1
>>> x[2:7] = np.arange(5)
>>> x[1] = 1.2
>>> x[1]
1
>>> x[1] = 1.2j
<type ’exceptions.TypeError’>: can’t convert complex to long; use
long(abs(z))
>>> x = np.arange(0, 50, 10)
>>> x
array([ 0, 10, 20, 30, 40])
>>> x[np.array([1, 1, 3, 1])] += 1
>>> x
array([ 0, 11, 20, 31, 40])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python numpy 数据