AppDividend
Latest Code Tutorials

Numpy flat: How to Use np flat() Function in Python

In Python, we know that we can create ndarray using Numpy. But if we want to iterate through the whole array and want the result in the 1D array, then we can use ndarray.flat() function. Numpy ndarray flat() function works like an iterator over the 1D array. Means, Numpy ndarray flat() method treats a ndarray as a 1D array and then iterates over it. The ndarray flat() function behaves similarly to Python iterator.

Syntax

ndarray.flat(range)

Parameters

In the above syntax: ndarray: is the name of the given array.

range: Indicates the range in which we want to print values.

Return Value

The ndarray flat() function returns 1D iteration of the given ndarray.

Programming Example

Working of ndarray.flat():

# importing numpy
import numpy as np

# Creating a 2D array using arange() of shape 3x5
arr = np.arange(15).reshape(3, 5)
print("The array is:\n ", arr)
print("Shape of the array is: ", np.shape(arr))

# Now we will print all the array values using flat()
print("All the array values using falt(): ")
print(arr.flat[0:15])

# Printing values in range 2 to 10
print("Array values of range 2-10: ")
print(arr.flat[2:11])

Output

The array is:
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]]
Shape of the array is:  (3, 5)
All the array values using falt():
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
Array values of range 2-10:
[ 2  3  4  5  6  7  8  9 10]

Explanation

In this example, we have created one 2D array of shape 3×5, and then we have printed all the values and shape of the array. Then we have printed the whole array, here we have given range 0 to 15, which returns the value from 0 to 14. Then also, we have printed values from 2 to 10.

Find the sum of array elements in a range of 2D array:

# importing numpy
import numpy as np

# Creating a 2D array using arange() of shape 3x5
arr = np.arange(15).reshape(3, 5)
print("The array is:\n ", arr)
print("Shape of the array is: ", np.shape(arr))

# Printing values in range 2 to 10
print("Array values of range 2-10: ")
print(arr.flat[2:11])

# Printing all sum of array values of range 2 to 10
arr2 = arr.flat[2:11]
print("Sum of array elements: ", np.sum(arr2))

Output

The array is:
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]]
Shape of the array is:  (3, 5)
Array values of range 2-10:
[ 2  3  4  5  6  7  8  9 10]
Sum of array elements:  54

Explanation

In this example, we have first created one 2D array of shape 5×3 then we have printed the values and shape of the array. Then we have printed values of range 2 to 10 also we have stored these values in arr2. Then we have printed the sum of the array elements using np.sum().

Finally, Numpy ndarray flat() example is over.