Python | Flatten a 2d numpy array into 1d array
Given a 2d numpy array, the task is to flatten a 2d numpy array into a 1d array. Below are a few methods to solve the task.
Method #1 : Using np.flatten()
# Python code to demonstrate # flattening a 2d numpy array # into 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = ini_array1.flatten() # printing result print("New resulting array: ", result) |
chevron_right
filter_none
Output:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [1 2 3 2 4 5 1 2 3]
Method #2: Using np.ravel()
# Python code to demonstrate # flattening a 2d numpy array # into 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = ini_array1.ravel() # printing result print("New resulting array: ", result) |
chevron_right
filter_none
Output:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [1 2 3 2 4 5 1 2 3]
Method #3: Using np.reshape()
# Python code to demonstrate # flattening a 2d numpy array # into 1d array import numpy as np ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) # printing initial arrays print("initial array", str(ini_array1)) # Multiplying arrays result = ini_array1.reshape([1, 9]) # printing result print("New resulting array: ", result) |
chevron_right
filter_none
Output:
initial array [[1 2 3] [2 4 5] [1 2 3]] New resulting array: [[1 2 3 2 4 5 1 2 3]]
Recommended Posts:
- Python | Numpy matrix.flatten()
- Python | Multiply 2d numpy array corresponding to 1d array
- Python | Reverse a numpy array
- Python | Replace negative value with zero in numpy array
- Python | Ways to add row/columns in numpy array
- Python | Find Mean of a List of Numpy Array
- Python | Filter out integers from float numpy array
- Python | dtype object length of Numpy array of strings
- Differences between Flatten() and Ravel() | Numpy
- Python | Ways to convert array of strings to array of floats
- Change data type of given numpy array
- Python | Flatten given list of dictionaries
- Python | Ways to flatten a 2D list
- Find the length of each string element in the Numpy array
- Modify Numpy array to store an arbitrary length string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



