w3resource

NumPy: Create an array which looks like below array

NumPy: Array Object Exercise-48 with Solution

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

# Creating a 4x3 array with values from 2 to 13 and generating an upper triangular matrix excluding the main diagonal (shifted by -1)
x = np.triu(np.arange(2, 14).reshape(4, 3), -1)

# Printing the resulting upper triangular matrix
print(x) 

Sample Output:

[[ 2  3  4]                                                            
 [ 5  6  7]                                                            
 [ 0  9 10]                                                            
 [ 0  0 13]]

Explanation:

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

x = np.tri(4, 3, -1): This 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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create an array which looks like below array.
Next: Write a NumPy program to collapse a 3-D array into one dimension 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.