w3resource

NumPy: Create an array which looks like below array


Create 2D Array with Specific Values

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.


For more Practice: Solve these Related Problems:

  • Construct a 2D array with specific values inserted at designated positions while other cells remain zero.
  • Write a function that builds an array from a list of row specifications and validates each row's content.
  • Use slicing to insert specific numeric values into an otherwise zero matrix and then verify the structure.
  • Create an array with a custom pattern of values and compare it with a pre-defined template for accuracy.

Go to:


PREV : Create Zero/One Array Template
NEXT : Collapse 3D Array to 1D


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.