w3resource

NumPy: Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements

NumPy: Array Object Exercise-170 with Solution

Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements. Write a NumPy program to find the number of occurrences of a sequence in the said array.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Creating a NumPy array with specific values and data type (np.int32)
np_array = np.array([[1, 2, 3], [2, 1, 2]], np.int32)

# Printing the original NumPy array and its type
print("Original NumPy array:")
print(np_array)
print("Type: ", type(np_array))

# Printing the sequence to search for in the NumPy array
print("Sequence: 1,2",)

# Counting the number of occurrences of the specified sequence "1, 2" in the array representation
result = repr(np_array).count("1, 2")

# Printing the number of occurrences of the specified sequence in the array
print("Number of occurrences of the said sequence:", result) 

Sample Output:

Original Numpy array:
[[1 2 3]
 [2 1 2]]
Type:  <class 'numpy.ndarray'>
Sequence: 1,2
Number of occurrences of the said sequence: 2

Explanation:

np_array = np.array([[1, 2, 3], [2, 1, 2]], np.int32) creates a 2x3 NumPy array with elements of type int32. np_array variable stores the created 2D array.

result = repr(np_array).count("1, 2")

In the above code -

  • repr(np_array) converts the NumPy array to its string representation. In this case, the string representation would be 'array([[1, 2, 3],\n [2, 1, 2]], dtype=int32)'.
  • count("1, 2") counts the number of occurrences of the sub-string "1, 2" in the string representation of the NumPy array.
  • 'result' variable stores the count of the sub-string occurrences.

Pictorial Presentation:

NumPy: Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements.

Python-Numpy Code Editor:

Previous: Write a NumPy program to get all 2D diagonals of a 3D NumPy array.
Next: Write a NumPy program to search the index of a given array in another given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-170.php