0
0
NumPydata~15 mins

flatten() and ravel() for 1D conversion in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Using flatten() and ravel() to Convert Arrays to 1D
📖 Scenario: Imagine you have a small photo represented as a 2D array of pixel brightness values. You want to convert this 2D photo into a simple list of pixels to analyze or store it easily.
🎯 Goal: You will create a 2D NumPy array, then use flatten() and ravel() methods to convert it into 1D arrays. Finally, you will print the results to see the difference.
📋 What You'll Learn
Create a 2D NumPy array with exact values
Create a variable to hold the flattened array using flatten()
Create a variable to hold the raveled array using ravel()
Print both 1D arrays to compare
💡 Why This Matters
🌍 Real World
Converting images or tables of data into a simple list helps in machine learning and data analysis tasks where flat input is needed.
💼 Career
Data scientists often reshape data arrays to prepare them for models or visualization tools.
Progress0 / 4 steps
1
Create a 2D NumPy array
Import NumPy as np and create a 2D NumPy array called photo with these exact values: [[10, 20, 30], [40, 50, 60]]
NumPy
Need a hint?

Use np.array() to create the 2D array with the exact nested list.

2
Create a flattened 1D array
Create a variable called flat_photo by applying the flatten() method on the photo array
NumPy
Need a hint?

Call flatten() on photo and assign it to flat_photo.

3
Create a raveled 1D array
Create a variable called ravel_photo by applying the ravel() method on the photo array
NumPy
Need a hint?

Call ravel() on photo and assign it to ravel_photo.

4
Print the flattened and raveled arrays
Print the variables flat_photo and ravel_photo each on its own line to see the 1D arrays
NumPy
Need a hint?

Use two print() statements, one for each variable.