📅  最后修改于: 2023-12-03 15:18:03.784000             🧑  作者: Mango
numpy.rollaxis()
函数是NumPy库中的一个用于重新排列数组轴的函数。该函数可用于改变数组的维度顺序,从而更好地与其他数组进行计算或操作。
numpy.rollaxis(arr, axis, start)
arr
: 输入的数组。axis
: 表示移动到新位置的轴。start
: 结果数组中维度的起始位置。默认值为0。返回移动轴后的新数组。
假设我们有一个3维数组 arr
,形状为 (3, 4, 5)。
import numpy as np
arr = np.random.rand(3, 4, 5)
print("原始数组:\n", arr)
输出:
原始数组:
[[[0.83159167 0.11873112 0.61040932 0.25983757 0.35832099]
[0.68542471 0.72475539 0.43419589 0.59444234 0.05585088]
[0.53492476 0.5244442 0.24071901 0.37258321 0.36367418]
[0.85145517 0.74371507 0.10481621 0.77889439 0.73666409]]
[[0.29091416 0.75093903 0.08915368 0.62983395 0.43298693]
[0.06352784 0.94238022 0.95806569 0.79582177 0.54066449]
[0.90217752 0.4633261 0.79198956 0.83414966 0.73533483]
[0.39933707 0.50002869 0.71615197 0.5522672 0.34949667]]
[[0.60190002 0.03388834 0.92070997 0.31473886 0.38331641]
[0.84166528 0.69753269 0.13692362 0.55157286 0.90748364]
[0.7035028 0.98738983 0.13983304 0.35310124 0.49448332]
[0.67972066 0.74928103 0.51882106 0.81421868 0.17401899]]]
new_arr = np.rollaxis(arr, 0, 3)
print("移动后的数组:\n", new_arr)
输出:
移动后的数组:
[[[0.83159167 0.29091416 0.60190002]
[0.11873112 0.75093903 0.03388834]
[0.61040932 0.08915368 0.92070997]
[0.25983757 0.62983395 0.31473886]
[0.35832099 0.43298693 0.38331641]]
[[0.68542471 0.06352784 0.84166528]
[0.72475539 0.94238022 0.69753269]
[0.43419589 0.95806569 0.13692362]
[0.59444234 0.79582177 0.55157286]
[0.05585088 0.54066449 0.90748364]]
[[0.53492476 0.90217752 0.7035028 ]
[0.5244442 0.4633261 0.98738983]
[0.24071901 0.79198956 0.13983304]
[0.37258321 0.83414966 0.35310124]
[0.36367418 0.73533483 0.49448332]]
[[0.85145517 0.39933707 0.67972066]
[0.74371507 0.50002869 0.74928103]
[0.10481621 0.71615197 0.51882106]
[0.77889439 0.5522672 0.81421868]
[0.73666409 0.34949667 0.17401899]]]
new_arr = np.rollaxis(arr, 2, 0)
print("移动后的数组:\n", new_arr)
输出:
移动后的数组:
[[[0.83159167 0.68542471 0.53492476 0.85145517]
[0.11873112 0.72475539 0.5244442 0.74371507]
[0.61040932 0.43419589 0.24071901 0.10481621]
[0.25983757 0.59444234 0.37258321 0.77889439]
[0.35832099 0.05585088 0.36367418 0.73666409]]
[[0.29091416 0.06352784 0.90217752 0.39933707]
[0.75093903 0.94238022 0.4633261 0.50002869]
[0.08915368 0.95806569 0.79198956 0.71615197]
[0.62983395 0.79582177 0.83414966 0.5522672 ]
[0.43298693 0.54066449 0.73533483 0.34949667]]
[[0.60190002 0.84166528 0.7035028 0.67972066]
[0.03388834 0.69753269 0.98738983 0.74928103]
[0.92070997 0.13692362 0.13983304 0.51882106]
[0.31473886 0.55157286 0.35310124 0.81421868]
[0.38331641 0.90748364 0.49448332 0.17401899]]]
numpy.rollaxis()
函数能够方便地重新排列数组的轴,使得进行计算和操作更加灵活和方便。更多关于该函数的详细信息和用法,请参考 NumPy官方文档。