python语法笔记

数组切片:
冒号分隔符:
功能:用于指定某一维度索引的区间范围

a[start:end] # 从数组中取索引start开始到end-1的记录
a[start:] # 取从start开始到末尾的元素
a[:end] # 取从0开始到end-1的元素
a[:] # 复制整个数组
a[start:end:step] #从start开始,每隔step取一个值,到不超过end为止
a[-1] #取最后一个值
a[-2:] #取最后两个值
a[:-2] #从0开始取到倒数第三个

逗号分隔符:
功能:用于区分处理的是第几维的数据

>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> b=a.reshape(2,2,3)
>>> b
array([[[ 0, 1, 2],
 [ 3, 4, 5]],

[[ 6, 7, 8],
 [ 9, 10, 11]]])
# 前面2个维度都取,第三个维度用数字2准确指定了下标索引值
>>> b[:,:,2] 
array([[ 2, 5],
 [ 8, 11]])
# 第1个维度都取,都2个维度只取索引从1开始,到(2-1)结束,第3维度只取索引值为1的值
>>> b[:,1:2,1] 
array([[ 4],
 [10]])
>>>

 

 

numpy 笔记

可视化教程

数组:

数组:

结论1: np.array()中,中括号有几层,就表示是几维数组

示例代码1:
>>> import numpy as np
>>> a=np.array([1,2,3,4,5])
>>> a.shape
(5,)
>>> a=np.array([[1,2,3,4,5]])
>>> a.shape
(1, 5)
>>> a=np.array([[1,2,3,4,5],[6,7,8,9,0]])
>>> a.shape
(2, 5)
>>> a[0]
array([1, 2, 3, 4, 5])
>>> a[1]
array([6, 7, 8, 9, 0])
>>> a[1][0]
6
>>>

示例代码2:

# :表示当前维的所有索引值都取
import numpy as np
t = np.array(
 [
 [0
 [0
 [1,2,3], 0
 [4,5,6] 1
 ], 
 [1
 [7,8,9], 0
 [10,11,12] 1
 ], 
 [2
 [13,14,15], 0 
 [16,17,18] 1
 ]
 ], 
 [1
 [0
 [19,20,21], 0
 [22,23,24] 1
 ], 
 [1
 [25,26,27], 0
 [28,29,30] 1
 ], 
 [2
 [31,32,33], 0
 [34,35,36] 1
 ]
 ]
 ])

>>> print(t[0,:,:,:])
[[[ 1 2 3]
 [ 4 5 6]]

[[ 7 8 9]
 [10 11 12]]

[[13 14 15]
 [16 17 18]]]

>>>print(t[:,0,:,:])
[[[ 1 2 3]
 [ 4 5 6]]

[[19 20 21]
 [22 23 24]]]

>>>print(t[:,:,0,:])
[[[ 1 2 3]
 [ 7 8 9]
 [13 14 15]]

[[19 20 21]
 [25 26 27]
 [31 32 33]]]

>>>print(t[:,:,:,0])
[[[ 1 4]
 [ 7 10]
 [13 16]]

[[19 22]
 [25 28]
 [31 34]]]

轴:axis
np.newaxis:
np.newaxis用于新插入一个轴,相当于新增一个数组维度

示例代码:
>>> a=np.array([1,2,3,4,5])
>>> a.shape
(5,)
>>> b=a[np.newaxis,:]
>>> b.shape
(1, 5)
>>> a
array([1, 2, 3, 4, 5])
>>> b
array([[1, 2, 3, 4, 5]])
>>> 
>>> c=a[:,np.newaxis]
>>> a.shape
(5,)
>>> c.shape
(5, 1)
>>> a
array([1, 2, 3, 4, 5])
>>> c
array([[1],
 [2],
 [3],
 [4],
 [5]])
>>>

numpy.expand_dims()
功能:同样是用于扩充数组维度
参数:
总共2个参数,
第一个表示基于哪个数组扩充,第二个表示在扩充后的元素在第几维

示例代码:
>>> a=np.arange(9)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> b=a.reshape(3,3)
>>> b
array([[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]])
>>> a.shape
(9,)
>>> b.shape
(3, 3)
>>> c=np.expand_dims(b,axis=0)
>>> c.shape
(1, 3, 3)
>>> c
array([[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]]])
>>> c[0][0]
array([0, 1, 2])
>>> c[0][0][1]
1
>>> 
>>> c=np.expand_dims(b,axis=1)
>>> c.shape
(3, 1, 3)
>>> c
array([[[0, 1, 2]],

[[3, 4, 5]],

[[6, 7, 8]]])
>>> c[0][0]
array([0, 1, 2])
>>> c[0][0][1]
1
>>> 
>>> c=np.expand_dims(b,axis=2)
>>> c.shape
(3, 3, 1)
>>> c
array([[[0],
 [1],
 [2]],

[[3],
 [4],
 [5]],

[[6],
 [7],
 [8]]])
>>>