w3resource

NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

NumPy: Array Object Exercise-42 with Solution

Write a NumPy program to create a 3-D array with ones on the diagonal and zeros elsewhere.

Pictorial Presentation:

Python NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

Sample Solution:-

Python Code:

import numpy as np
x = np.eye(3)
print(x)

Sample Output:

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

Python Code Editor:

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

Previous: Write a NumPy program to create an array of 10's with the same shape and type of an given array.
Next: Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}