Przykłady transpozycji w bibliotece NumPy:
- Transpozycja tablicy 2D:
import numpy as np
# Tworzenie tablicy 3x3
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
# Transpozycja tablicy
a_t = a.T
print(a_t)
# [[1 4 7]
# [2 5 8]
# [3 6 9]]
2. Transpozycja tablicy 3D:
import numpy as np
# Tworzenie tablicy 3x3x3
a = np.arange(27).reshape((3,3,3))
print(a)
# [[[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]]
#
# [[ 9 10 11]
# [12 13 14]
# [15 16 17]]
#
# [[18 19 20]
# [21 22 23]
# [24 25 26]]]
# Transpozycja tablicy
a_t = np.transpose(a, (1, 2, 0))
print(a_t)
# [[[ 0 9 18]
# [ 1 10 19]
# [ 2 11 20]]
#
# [[ 3 12 21]
# [ 4 13 22]
# [ 5 14 23]]
#
# [[ 6 15 24]
# [ 7 16 25]
# [ 8 17 26]]]
3. Transpozycja macierzy 4D:
import numpy as np
# Tworzenie tablicy 4x3x2x2
a = np.arange(24).reshape((4,3,2,2))
print(a)
# [[[[ 0 1]
# [ 2 3]]
#
# [[ 4 5]
# [ 6 7]]
#
# [[ 8 9]
# [10 11]]]
#
#
# [[[12 13]
# [14 15]]
#
# [[16 17]
# [18 19]]
#
# [[20 21]
# [22 23]]]
#
#
# [[[24 25]
# [26 27]]
#
# [[28 29]
# [30 31]]
#
# [[32 33]
# [34 35]]]
#
#
# [[[36 37]
# [38 39]]
#
# [[40 41]
# [42 43]]
#
# [[44 45]
# [46 47]]]]
# Transpozycja tablicy
a_t = np.transpose(a, (2, 3, 0, 1))
print(a_t)
# [[[[ 0 4 8]
# [12 16 20]
# [24 28 32]
# [36 40 44]]
#
# [[ 1 5 9]
# [13 17 21]
# [25 29 33]
# [37 41 45]]]
#
#
# [[[ 2 6 10]
# [14 18 22]
# [26 30 34]
# [38 42 46]]
#
# [[ 3 7 11]
# [15 19 23]
# [27 31 35]
# [39 43 47]]]]