1import numpy as np
2
3# 1D array
4one_dim_arr = np.array([1, 2, 3, 4, 5, 6])
5
6# to convert to 2D array
7# we can use the np.ndarray.reshape(shape) function
8# here shape is given by two integers seperated by a comma
9# the two integers specify m,n for the new matrix
10# ensure that the matrix that you are trying to generate
11# has a size that meets the number of elements in the 1D array.
12# for that make sure that
13# m * n = number of elements in the one dimentional array
14
15two_dim_arr = one_dim_arr.reshape(1, 6)
16
17#which returns a 2D array
18print(two_dim_arr)
19
20
21# confirmed by the array.ndim attribute
22print(two_dim_arr.ndim)
23
24# you can even specify one of the dimensions as unknown by passing -1
25# numpy will infer the length using the array and remaining dimensions
26
27two_dim_arr = one_dim_arr.reshape(1,-1)
1# Create a 2D Numpy Array.
2arr = np. array([[0, 1, 2],
3[3, 4, 5],
4[6, 7, 8]])
5# convert 2D array to a 1D array of size 9.
6flat_arr = np. reshape(arr, 9)
7