NumPy: Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements
Count occurrences of sequences in a 2D array.
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:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics