w3resource

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:

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to count how many times a given sub-sequence appears in each row of a 2D array.
  • Create a function that uses convolution to detect and count the occurrences of a specified sequence.
  • Implement a solution that slides a window over each row of a 2D array and tallies matches to the target sequence.
  • Test the sequence counting on arrays with overlapping sequences to ensure accurate counting.

Go to:


PREV : Extract all 2D diagonals of a 3D array.
NEXT : Search for a sub-array in a larger array.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.