Friday, October 24, 2025
HomeLanguagesPython | Flatten a 2d numpy array into 1d array

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() 

Python3




# 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)


Output:

initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [1 2 3 2 4 5 1 2 3]

Time complexity: O(n), where n is the total number of elements in the 2D numpy array.
Auxiliary space: O(n), as the result array is also of size n. The flatten function returns a flattened 1D array, which is stored in the “result” variable.

Method #2: Using np.ravel() 

Python3




# 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)


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() 

Python3




# 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)


Output:

initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[1 2 3 2 4 5 1 2 3]]

Time Complexity: O(n), where n is the total number of elements in the 2D numpy array.
Auxiliary Space: O(n), as the program creates a new 1D list with the same number of elements as the original 2D array.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS