0 votes
in Python by
explain numpy.ndarray.flat() in Python

1 Answer

0 votes
by

numpy.ndarray.flat() in Python

The numpy.ndarray.flat() returns a 1-D iterator over the array. This function is not a subclass of, Python’s built-in iterator object, otherwise it will act the same as a numpy.flatiter instance.

Syntax

ndarray.flat()

Parameter

NA

Return

This function returns a 1-D iteration of an array.

Example 1

# Python Program explaining
# numpy.ndarray.flat() function
import numpy as np 
# 1D iteration of 2D array 
arr = np.arange(20).reshape(4, 5)
print("2D array : \n",arr )
# Using flat() to return 1D iterator over range
print("Using Array: \n", arr.flat[2:8])
# Using flat() for 1D repersented array
print("1D array: \n ->", arr.flat[3:15])

Output

2D array :
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]
[15 16 17 18 19]]
Using Array:
[2 3 4 5 6 7]
1D array:
-> [ 3  4  5  6  7  8  9 10 11 12 13 14]

Example 2

# Python Program explaining
# numpy.ndarray.flat() function
import numpy as np 
# 1D iteration of 2D array 
array = np.arange(20).reshape(4, 5)
print("2D array : \n",array )
# All values set to 1
array.flat = 1
print("Values set to 1 : \n", array)
array.flat[3:6] = 8
array.flat[8:10] = 9
print("Altering the values in a range : \n", array)

Output

2D array :
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]
[15 16 17 18 19]]
Values set to 1 :
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
Altering the values in a range :
[[1 1 1 8 8]
[8 1 1 9 9]
[1 1 1 1 1]
[1 1 1 1 1]]

Related questions

0 votes
asked May 19, 2022 in Python by john ganales
0 votes
asked May 19, 2022 in Python by john ganales
...