This is the 26th day of my participation in the August More Text Challenge
1. Array remodeling
Array reshaping is changing the shape of an array. For example, an array with 3 rows and 4 columns can be reconfigured to have 4 rows and 3 columns. 0 0 array remodeling in numpy
1.1 One-dimensional array remodeling
One-dimensional array reshaping is to reshape an array from a single row or column to a multi-row and multi-column array.
Let’s create a one-dimensional array
import numpy as np
arr = np.arange(8)
print(arr)
Copy the code
result:
[0 1 2 3 4 5 6 7]
Copy the code
The array above 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 2-row, 4-column multidimensional array
print(arr.reshape(2, 4))
Copy the code
result:
[0 1 2 3] [4 5 6 7]]Copy the code
1.1.2 Reshape an array into a multidimensional array with 4 rows and 2 columns
print(arr.reshape(4, 2))
Copy the code
result:
[1] [2 3] [4 5] [6 7]]Copy the code
Note: Regardless of 2 rows and 4 columns or 4 rows and 2 columns, as long as the number of values in the reshaped array is equal to the number of values in the previous one-dimensional array.
1.2 Multidimensional Array remodeling
Let’s create a multidimensional array
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(arr)
Copy the code
result:
[1 2 3] [4 5 6] [7 8 9] [10 11 12]Copy the code
Similarly, the array above can be converted to either a 3-row, 4-column multidimensional array or a 2-row, 6-column multidimensional array
1.2.1 Reshape an array into a multidimensional array with 3 rows and 4 columns
print(arr.reshape(3, 4))
Copy the code
result:
[12 3 4] [5 6 7 8] [9 10 11 12]Copy the code
1.2.2 Reshape an array into a 2-row, 6-column multidimensional array
print(arr.reshape(2, 6))
Copy the code
result:
[12 3 4 5 6] [7 8 9 10 11 12]Copy the code
Note: We can also reshape a multidimensional array with 4 rows and 3 columns into a multidimensional array with 3 rows and 4 columns or 2 rows and 6 columns, as long as the number of values in the reshaped array is equal to the number of values in the previous one-dimensional array.
2. Array transpose
Array transpose is the process of turning rows of an array into columns. T. You can think of the transpose here as a special kind of remolding.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(arr)
Copy the code
result:
[1 2 3] [4 5 6] [7 8 9] [10 11 12]Copy the code
print(arr.T)
Copy the code
result:
[1 4 7 10] [2 5 8 11] [3 6 9 12]Copy the code