w3resource

NumPy: Create a contiguous flattened array


Flatten Array

Write a NumPy program to create a contiguous flattened array.

Pictorial Presentation:

Python NumPy: Create a contiguous flattened array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 2D NumPy array with two rows and three columns
x = np.array([[10, 20, 30], [20, 40, 50]])
# Displaying the original array
print("Original array:")
print(x)

# Flattening the array 'x' into a 1D array using np.ravel
y = np.ravel(x)
# Displaying the flattened array 'y'
print("New flattened array:")
print(y) 

Sample Output:

Original array:                                                        
[[10 20 30]                                                            
 [20 40 50]]                                                           
New flattened array:                                                   
[10 20 30 20 40 50] 

Explanation:

In the above exercise -

x = np.array([[10, 20, 30], [20, 40, 50]]): This line creates a two-dimensional NumPy array ‘x’ with two rows and three columns.

print(x): This line prints the ‘x’ array, which has the shape (2, 3) and contains the specified elements.

y = np.ravel(x): This line flattens the two-dimensional array ‘x’ into a one-dimensional array y using the np.ravel() function.

print(y): This line prints the flattened one-dimensional array ‘y’, which contains the elements [10, 20, 30, 20, 40, 50].


For more Practice: Solve these Related Problems:

  • Flatten a multi-dimensional array using both np.flatten and np.ravel and compare their outputs.
  • Create a function that collapses an array into 1D and then reconstructs the original shape using reshape.
  • Verify that the order of elements in the flattened array is consistent with row-major ordering.
  • Test flattening on non-contiguous arrays and analyze the differences in performance and output.

Go to:


PREV : Change Array Dimensions
NEXT : Create 2D Array & Print Shape/Type


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.