numpy 中强大的 transpose() 、rollaxis()、swapaxes()

在numpy中,有三个方法对数组进行维度的变换,非常的强大,简直太酷了。

1. transpose() 翻转数组的维度顺序

        意思是,假设有个3维数组,array[x][y][z],x,y,z是他的三个维度,那么翻转后就变成了 array[z][y][x]。我们用代码测试一下:

import numpy as np
data = [[[1,2,3],[4,5,6],[7,8,9]], 
        [[11,22,33],[44,55,66],[77,88,99]], 
        [[111,222,333],[444,555,666],[777,888,999]], 
        [[1111,2222,3333],[4444,5555,6666],[7777,8888,9999]]
        ]
ndarray = np.array(data)

ndarray 打印出来是这样的:

array([[[   1,    2,    3],
        [   4,    5,    6],
        [   7,    8,    9]],

       [[  11,   22,   33],
        [  44,   55,   66],
        [  77,   88,   99]],

       [[ 111,  222,  333],
        [ 444,  555,  666],
        [ 777,  888,  999]],

       [[1111, 2222, 3333],
        [4444, 5555, 6666],
        [7777, 8888, 9999]]])

执行 ndarray.transpose(), 打印出来是这样的:

array([[[   1,   11,  111, 1111],
        [   4,   44,  444, 4444],
        [   7,   77,  777, 7777]],

       [[   2,   22,  222, 2222],
        [   5,   55,  555, 5555],
        [   8,   88,  888, 8888]],

       [[   3,   33,  333, 3333],
        [   6,   66,  666, 6666],
        [   9,   99,  999, 9999]]])

我们用下面的代码实现一下,就很好理解了。

nda1 = numpy.zeros((3,3,4), dtype=numpy.int32)
"""
这里为什么是 (3,3,4),是因为原数组是 (4, 3, 3).   transpose 翻转,就是把维度的顺序反过来。
"""

for z in range(3):
    for y in range(3):
        for x in range(4):
            nda1[z,y,x] = ndarray[x,y,z]

打印 nda1 ,你会发现输出的结果就是 transpose() 后的样子。这是就是翻转

2. rollaxis(arr, axis, start) 将数组arr所对应的axis轴 放在 start轴的前面,start轴往后移一“列” 

意思是,假设还是有个3维数组,array[x][y][z],rollaxis(array, z, x) -> array[z][x][y]

我们可以列出3维数组的所有可能:

rollaxis(array, x, x) -> array[x][y][z]

rollaxis(array, x, y) -> array[x][y][z]

rollaxis(array, x, z) -> array[y][x][z]

rollaxis(array, y, x) -> array[y][x][z]

rollaxis(array, y, y) -> array[x][y][z]

rollaxis(array, y, z) -> array[x][y][z]

rollaxis(array, z, x) -> array[z][x][y]

rollaxis(array, z, y) -> array[x][z][y]

rollaxis(array, z, z) -> array[x][y][z]

我们还是用代码实现一下:rollaxis(array, 2, 0) -> array[z][x][y],看看是否正确

# 注意 原数组是 (4, 3, 3),新的结构就是(3,4,3)

nda2 = numpy.zeros((3,4,3), dtype=numpy.int32)  
for z in range(3):
    for x in range(4):
        for y in range(3):
            nda2[z,x,y] = ndarray[x,y,z]

我们可打印出来:nda2 的值 和 numpy.rollaxis(ndarray, 2, 0) 是一样的。

3. swapaxes(arr, axis1, axis2) 交换数组的两个轴

这个就比较好理解了。我们用代码实现一下,交换一下 x 轴和 z 轴

# 注意 原数组是 (4, 3, 3),交换后的新的结构就是(3,3,4)

nda3 = numpy.zeros((3,3,4), dtype=numpy.int32)  
for z in range(3):
    for y in range(3):
        for x in range(4):
            nda3[z,y,x] = ndarray[x,y,z]

 打印出 nda3 的值,看看是不是和 np.swapaxes(ndarray, 0, 2) 是一样的。

确实,numpy中对多维数组的旋转轴操作,实在是太方便了。

你可以使用 Python 的内置函数 `dir()` 来查看一个库(模块)中所有的函数变量。例如,如果你想查看 NumPy 库中的所有函数变量,可以在 Python 中输入以下代码: ```python import numpy as np print(dir(np)) ``` 这将会打印出 NumPy 库中所有的函数变量名称,如下所示: ``` ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'absolute', 'absolute_import', 'add', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'beta', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool', 'bool8', 'broadcast', 'broadcast_arrays', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'bytes', 'bytes0', 'bytes_', 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'chararray', 'choose', 'clip', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex', 'complex128', 'complex64', 'complex_', 'compress', 'concatenate', 'conjugate', 'contains', 'convolve', 'copy', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'deg2rad', 'degrees', 'delete', 'deprecate', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'einsum', 'elect', 'element_wise', 'empty', 'empty_like', 'equal', 'errstate', 'exp', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flat', 'flatiter', 'flatten', 'fliplr', 'flipud', 'float', 'float128', 'float16', 'float32', 'float64', 'float_', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'fv', 'gcd', 'generic', 'genfromtxt', 'get_array_wrap', 'get_include', 'get_numarray_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'ifft', 'imag', 'in1d', 'index_exp', 'indices', 'inf', 'info', 'inner', 'insert', 'int', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'integer', 'interp', 'intersect1d', 'intersect1d_nu', 'intp', 'invert', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'lstsq', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nanwarnings', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'np', 'numarray', 'number', 'obj2sctype', 'object', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'pinv', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'ppmt', 'print_function', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'pv', 'quantile', 'r_', 'rad2deg', 'radians', 'random', 'rank', 'rate', 'ravel', 'real', 'real_if_close', 'recarray', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'sinh', 'size', 'slice', 'solve', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str', 'str0', 'str_', 'subtract', 'sum', 'svd', 'swapaxes', 'sys', 'take', 'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typeDict', 'typeNA', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'union1d', 'unique', 'unique1d', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'warnings', 'weibull', 'where', 'who', 'zeros', 'zeros_like'] ``` 注意,`dir()` 会输出所有名称,包括 Python 内置函数、变量 NumPy 模块中的名称。如果你只想查看 NumPy 模块中的名称,你可以使用 `dir(np.core)`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值