27 lines
1.2 KiB
Python
27 lines
1.2 KiB
Python
import numpy as np
|
|
"""
|
|
This script demonstrates three different methods to flatten a NumPy array:
|
|
1. `flatten()`: Returns a copy of the array collapsed into one dimension.
|
|
2. `reshape(-1)`: Reshapes the array into a one-dimensional array.
|
|
3. `ravel()`: Returns a flattened array; returns a view whenever possible.
|
|
The script uses a simulated exam scores array for three students across three subjects.
|
|
It prints the results of each flattening method and shows that modifying the copy returned by `flatten()` does not affect the original array.
|
|
"""
|
|
# Simulated exam scores for three students in three subjects
|
|
exam_scores = np.array([[75, 82, 90], [92, 88, 78], [60, 70, 85]])
|
|
# Use the flatten() method for flattening
|
|
flattened_exam_scores = exam_scores.flatten()
|
|
print(flattened_exam_scores)
|
|
|
|
# Use the reshape() method for flattening
|
|
exam_scores_reshaped = exam_scores.reshape(-1)
|
|
print(exam_scores_reshaped)
|
|
|
|
# Use the ravel() method for flattening
|
|
exam_scores_raveled = exam_scores.ravel()
|
|
print(exam_scores_raveled)
|
|
|
|
# Set the first element of the flattened copy to 100
|
|
flattened_exam_scores[0] = 100
|
|
print(flattened_exam_scores)
|
|
print(exam_scores) # Original array remains unchanged |