python中numpy.moveaxis以及numpy.expand_dims的用法介绍

本文详细介绍了NumPy库中moveaxis函数与expand_dims函数的使用方法。moveaxis用于改变数组轴的位置,而expand_dims用于在指定位置增加新的轴。通过多个实例展示了如何使用这些函数来重新组织数组的维度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. numpy. moveaxis ( asourcedestination ) [source]

Move axes of an array to new positions.

Other axes remain in their original order.

New in version 1.11.0.

Parameters:

a : np.ndarray

The array whose axes should be reordered.

source : int or sequence of int

Original positions of the axes to move. These must be unique.

destination : int or sequence of int

Destination positions for each of the original axes. These must also be unique.

Returns:

result : np.ndarray

Array with moved axes. This array is a view of the input array.

See also

transpose
Permute the dimensions of an array.
swapaxes
Interchange two axes of an array.

Examples

>>> x = np.zeros((3, 4, 5))
>>> np.moveaxis(x, 0, -1).shape
(4, 5, 3)
>>> np.moveaxis(x, -1, 0).shape
(5, 3, 4)

These all achieve the same result:

>>> np.transpose(x).shape
(5, 4, 3)
>>> np.swapaxes(x, 0, -1).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1], [-1, -2]).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
(5, 4, 3)

2.expand_dims(a, axis)

就是在axis的那一个轴上把数据加上去,这个数据在axis这个轴的0位置。 

例如原本为一维的2个数据,axis=0,则shape变为(1,2),axis=1则shape变为(2,1) 

再例如 原本为 (2,3),axis=0,则shape变为(1,2,3),axis=1则shape变为(2,1,3)

numpy. expand_dims ( aaxis ) [source]

Expand the shape of an array.

Insert a new axis that will appear at the axis position in the expanded array shape.

Note

Previous to NumPy 1.13.0, neither axis < -a.ndim - 1 nor axis > a.ndim raised errors or put the new axis where documented. Those axis values are now deprecated and will raise an AxisError in the future.

Parameters:

a : array_like

Input array.

axis : int

Position in the expanded axes where the new axis is placed.

Returns:

res : ndarray

Output array. The number of dimensions is one greater than that of the input array.

See also

squeeze
The inverse operation, removing singleton dimensions
reshape
Insert, remove, and combine dimensions, and resize existing ones

doc.indexingatleast_1datleast_2datleast_3d

Examples

>>> x = np.array([1,2])
>>> x.shape
(2,)

The following is equivalent to x[np.newaxis,:] or x[np.newaxis]:

>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1)  # Equivalent to x[:,np.newaxis]
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)

Note that some examples may use None instead of np.newaxis. These are the same objects:

>>> np.newaxis is None
True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值