Realization of Array Remodeling in numpy Series
- 2021-11-29 07:24:43
- OfStack
1.2 Multidimensional array remodeling
2. Array transpose
1. Array remodeling
Array remodeling is to change the shape of an array. For example, the original array with 3 rows and 4 columns is reshaped into an array with 4 rows and 3 columns. Realization of array remodeling by reshape method in numpy
1.1 1-dimensional array remodeling
1-dimensional array remodeling is to reshape an array from a 1-row or 1-column array to a multi-row and multi-column array.
Create a 1-dimensional array first
import numpy as np
arr = np.arange(8)
print(arr)
result:
[0 1 2 3 4 5 6 7]
The above array can be converted to either a 2-row 4-column multidimensional array or a 4-row 2-column multidimensional array
1.1. 1 Reshape an array into a multidimensional array with 2 rows and 4 columns
print(arr.reshape(2, 4))
result:
[[0 1 2 3]
[4 5 6 7]]
1.1. 2 Rebuilding an array to a multidimensional array with 4 rows and 2 columns
print(arr.reshape(4, 2))
result:
[[0 1]
[2 3]
[4 5]
[6 7]]
Note: No matter 2 rows and 4 columns or 4 rows and 2 columns, as long as the number of values in the array after remodeling is equal to the number of values in the 1-dimensional array before remodeling.
1.2 Multidimensional array remodeling
Create a multidimensional array first
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(arr)
result:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Similarly, the above array can be converted to either a 3-row, 4-column multidimensional array or a 2-row, 6-column multidimensional array
1.2. 1 Rebuilding an array to a multidimensional array with 3 rows and 4 columns
print(arr.reshape(3, 4))
result:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
1.2. 2 Reshape the array into a multidimensional array with 2 rows and 6 columns
print(arr.reshape(2, 6))
result:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Note: We can also reshape a 4-row 3-column multidimensional array into a 3-row 4-column or 2-row 6-column multidimensional array, as long as the number of values in the reshaped array is equal to the number of values in the previous 1-dimensional array.
2. Array transpose
Array transposition is to rotate the rows of an array into columns, using the method of. T. Transposition can be regarded as a special kind of remodeling here.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(arr)
result:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
print(arr.T)
result:
[[ 1 4 7 10]
[ 2 5 8 11]
[ 3 6 9 12]]