w3resource

NumPy: Create an array of (3, 4) shape and convert the array elements in smaller chunks

NumPy: Array Object Exercise-77 with Solution

Write a NumPy program to create an array of (3, 4) shapes and convert the array elements into smaller chunks.

Pictorial Presentation:

Python NumPy: Create an array of (3, 4) shape and convert the array elements in smaller chunks

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a 1-dimensional array 'x' with values from 0 to 11 and reshaping it into a 3x4 array
x = np.arange(12).reshape(3, 4)

# Printing a message indicating the original array elements will be shown
print("Original array elements:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the array will be displayed in small chunks
print("Above array in small chunks:")

# Using np.nditer to iterate through the array 'x' in Fortran order with external loop
# Iterating through 'x' in a way that external_loop flag generates chunks of elements in the Fortran order
for a in np.nditer(x, flags=['external_loop'], order='F'):
    print(a)  # Printing each chunk 

Sample Output:

Original array elements:                                               
[[ 0  1  2  3]                                                         
 [ 4  5  6  7]                                                         
 [ 8  9 10 11]]                                                        
Above array in small chuncks:                                          
[0 4 8]                                                                
[1 5 9]                                                                
[ 2  6 10]                                                             
[ 3  7 11]

Explanation:

x= np.arange(12).reshape(3, 4): Create an array x with values from 0 to 11, and reshape it into a 3x4 array.

for a in np.nditer(x, flags=['external_loop'], order='F'):: Use np.nditer to create an iterator for array x. Set the flags parameter to include 'external_loop', which allows for iterating over larger chunks of the array at once, based on memory layout. Set the order parameter to 'F' to iterate over the array in Fortran/column-major order (i.e., column by column).

Finally print(a) prints the current chunk in the iteration.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a function cube which cubes all the elements of an array.
Next: Write a NumPy program to create a record array from a (flat) list of arrays.

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.