当前位置: 首页 > 文档资料 > NumPy 中文教程 >

expand_dims

优质
小牛编辑
157浏览
2023-12-01

此函数通过在指定位置插入新轴来扩展阵列。 该功能需要两个参数。

numpy.expand_dims(arr, axis)

Where,

Sr.No.参数和描述
1

arr

输入数组

2

axis

插入新轴的位置

例子 (Example)

import numpy as np 
x = np.array(([1,2],[3,4])) 
print 'Array x:' 
print x 
print '\n'  
y = np.expand_dims(x, axis = 0) 
print 'Array y:' 
print y 
print '\n'
print 'The shape of X and Y array:' 
print x.shape, y.shape 
print '\n'  
# insert axis at position 1 
y = np.expand_dims(x, axis = 1) 
print 'Array Y after inserting axis at position 1:' 
print y 
print '\n'  
print 'x.ndim and y.ndim:' 
print x.ndim,y.ndim 
print '\n'  
print 'x.shape and y.shape:' 
print x.shape, y.shape

上述方案的产出如下 -

Array x:
[[1 2]
 [3 4]]
Array y:
[[[1 2]
 [3 4]]]
The shape of X and Y array:
(2, 2) (1, 2, 2)
Array Y after inserting axis at position 1:
[[[1 2]]
 [[3 4]]]
x.ndim and y.ndim:
2 3
x.shape and y.shape:
(2, 2) (2, 1, 2)