python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
print(arr.shape)
print(arr.ndim)
print('###############')
arr2 = np.array([1, 2, 3, 4 ,5 ,6])
print(arr2)
print(arr2.shape)
print(arr.ndim)
print('###############')
arr3 = arr2.reshape(3, 2)
print(arr3)
print(arr3.shape)
print(arr3.ndim)
print('###############')
arr3 = arr2.reshape(3, -1)
print(arr3)
print(arr3.shape)
print(arr3.ndim)
Execution result
[[1 2 3]
[4 5 6]]
(2, 3)
2
###############
[1 2 3 4 5 6]
(6,)
2
###############
[[1 2]
[3 4]
[5 6]]
(3, 2)
2
###############
[[1 2]
[3 4]
[5 6]]
(3, 2)
2
You can get the shape in the form of (row, column) with shpe. You can use ndim to get the number of dimensions of a multidimensional array.
Use the reshape () method to change the shape. Specify the shape in the form of (row, column) in the argument of reshape ().
The array after changing the shape with reshape and the original array must have the same number of elements. In the above example, the array arr2 has 6 elements. It can be reshaped with arr.reshape ((2, 3)). (Because 2 x 3 = 6) If the number of elements is different, ValueError will occur.
By passing 3 and -1 as the argument of reshape, a 3x2 array is automatically generated.
Recommended Posts