w3resource

NumPy: Create and display every element of a numpy array in Fortran order

NumPy: Array Object Exercise-71 with Solution

Write a NumPy program to create and display every element of a NumPy array in Fortran order.

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 elements of the array will be iterated in Fortran order
print("Elements of the array in Fortran array:")

# Using a loop with np.nditer to iterate through each element in the array 'x' in Fortran order
# Printing each element followed by a space and keeping the output in the same line due to the 'end' parameter
for x in np.nditer(x, order="F"):
    print(x, end=' ')

# Printing a newline character to move to the next line after the loop completes
print("\n")

Sample Output:

Elements of the array in Fortan array:                                 
0 4 8 1 5 9 2 6 10 3 7 11   

Explanation:

In the above code -

‘x = np.arange(12).reshape(3, 4)’ creates a 1D NumPy array with elements from 0 to 11 using np.arange(), and then reshapes it into a 3x4 array using reshape(3, 4) and stores it in the variable ‘x’.

for x in np.nditer(x, order="F"):: This line iterates through each element in the reshaped array using np.nditer() with the order="F" argument. The "F" indicates Fortran order, which means the iteration will be performed column by column (column-major order).

print(x, end=' '): Inside the loop, this line prints the current element followed by a space (the end=' ' argument ensures that the elements are printed on the same line separated by spaces).

Python-Numpy Code Editor:

Previous: Write a NumPy program to create and display every element of a numpy array.
Next: Write a NumPy program to create a 5x5x5 cube of 1's.

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.