w3resource

NumPy: Create an array which looks like below array


Create Zero/One Array Template

Write a NumPy program to create an array like the one below.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Generating a lower-triangular matrix of size 4x3 with ones on and below the main diagonal shifted by -1
x = np.tri(4, 3, -1)

# Printing the generated matrix
print(x) 

Sample Output:

[[ 0.  0.  0.]                                                         
 [ 1.  0.  0.]                                                         
 [ 1.  1.  0.]                                                         
 [ 1.  1.  1.]]

Explanation:

The above code demonstrates how to create a NumPy array using the np.tri() function.

x = np.tri(4, 3, -1): The current line creates a NumPy array x using the np.tri() function. The function takes three arguments: the number of rows (4), the number of columns (3), and the diagonal below which the elements should be set to 1 (-1). The array is created with ones at and below the specified diagonal and zeros elsewhere.


For more Practice: Solve these Related Problems:

  • Create a 2D array template with the top half filled with zeros and the bottom half with ones.
  • Write a function that generates an array with alternating rows of zeros and ones based on a given number of rows.
  • Validate the pattern by checking that every even-indexed row contains only zeros and odd-indexed rows only ones.
  • Extend the template to allow for custom binary patterns and verify the output with assertions.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 1-D array of 20 element spaced evenly on a log scale between 2. and 5., exclusive.
Next: Write a NumPy program to create an array which looks like below array.

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.