There are 3 methods to convert 2-D arrays to 1-D ones in Numpy. The following shows the key syntax.
Method 1:
numpy.ravel()
Method 2:
ndarray.flatten(order=’C’)
Method 3:
ndarray.reshape(-1)
Example 1 (Method 1):
We can use numpy.ravel() to convert 2-D arrays to 1-D ones. Below is the example.
# import numpy
import numpy as np
# Create a 2-D numpy array of data:
X = np.array([[5, 2, 3, 4, 10, 11, 14],[3, 1, 2, 5, 14, 15, 16]])
print('2-D array:\n',X)
# convert 2-D array to 1-D using ravel()
X=X.ravel()
print('1-D array:\n',X)
Output:
2-D array: [[ 5 2 3 4 10 11 14] [ 3 1 2 5 14 15 16]] 1-D array: [ 5 2 3 4 10 11 14 3 1 2 5 14 15 16]
Example 2 (Method 2):
We can also use the ndarray.flatten() to convert 2-D arrays to 1D ones. The following is the example.
# import numpy
import numpy as np
# Create a 2-D numpy array of data:
X = np.array([[5, 2, 3, 4, 10, 11, 14],[3, 1, 2, 5, 14, 15, 16]])
print('2-D array:\n',X)
# convert 2-D array to 1-D using flatten()
X=X.flatten(order='C')
print('1-D array:\n',X)
Output:
2-D array: [[ 5 2 3 4 10 11 14] [ 3 1 2 5 14 15 16]] 1-D array: [ 5 2 3 4 10 11 14 3 1 2 5 14 15 16]
Example 3 (Method 3):
We can also use reshape() to convert 2-D arrays to 1D ones. The following is the example.
# import numpy
import numpy as np
# Create a 2-D numpy array of data:
X = np.array([[5, 2, 3, 4, 10, 11, 14],[3, 1, 2, 5, 14, 15, 16]])
print('2-D array:\n',X)
# convert 2-D array to 1-D using reshape()
X=X.reshape(-1)
print('1-D array:\n',X)
Output:
2-D array: [[ 5 2 3 4 10 11 14] [ 3 1 2 5 14 15 16]] 1-D array: [ 5 2 3 4 10 11 14 3 1 2 5 14 15 16]