一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情。
np数组的变形与合并
【a】转置:T
np.zeros((2,3)).T
array([[0., 0.],
[0., 0.],
[0., 0.]])
【b】合并操作:r_, c_
对于二维数组而言,r_和c_分别表示上下合并和左右合并:
np.r_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
np.c_[np.zeros((2,3)),np.zeros((2,3))]
array([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])
一维数组和二维数组进行合并时,应当把其视作列向量,在长度匹配的情况下只能够使用左右合并的c_操作:
try:
np.r_[np.array([0,0]),np.zeros((2,1))]
except Exception as e:
Err_Msg = e
Err_Msg
ValueError('all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)')
np.r_[np.array([0,0]),np.zeros(2)]
array([0., 0., 0., 0.])
np.c_[np.array([0,0]),np.zeros((2,3))]
array([[0., 0., 0., 0.],
[0., 0., 0., 0.]])
【c】维度变换:reshape
reshape能够帮助用户把原数组按照新的维度重新排列。在使用时有两种模式,分别为C模式和F模式,分别以逐行和逐列的顺序进行填充读取。
target = np.arange(8).reshape(2,4)
target
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
target.reshape((4,2), order='C') # 按照行读取和填充
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
target.reshape((4,2), order='F') # 按照列读取和填充
array([[0, 2],
[4, 6],
[1, 3],
[5, 7]])
特别地,由于被调用数组的大小是确定的,reshape允许有一个维度存在空缺,此时只需填充-1即可:
target.reshape((4,-1))
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
下面将n*1大小的数组转为1维数组的操作是经常使用的:
target = np.ones((3,1))
target
array([[1.],
[1.],
[1.]])
target.reshape(-1)
array([1., 1., 1.])
3. np数组的切片与索引
数组的切片模式支持使用slice类型的start:end:step切片,还可以直接传入列表指定某个维度的索引进行切片:
target = np.arange(9).reshape(3,3)
target
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
target[:-1, [0,2]]
array([[0, 2],
[3, 5]])
此外,还可以利用np.ix_在对应的维度上使用布尔索引,但此时不能使用slice切片:
target[np.ix_([True, False, True], [True, False, True])]
array([[0, 2],
[6, 8]])
target[np.ix_([1,2], [True, False, True])]
array([[3, 5],
[6, 8]])
当数组维度为1维时,可以直接进行布尔索引,而无需np.ix_:
new = target.reshape(-1)
new[new%2==0]
array([0, 2, 4, 6, 8])