Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Flatten a 2d numpy array into 1d array

  • Difficulty Level : Basic
  • Last Updated : 15 Mar, 2019

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




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

 
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)
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)
Output:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[1 2 3 2 4 5 1 2 3]]



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!