Create 2D Array in NumPy

NumPy – Create 2D Array

To create a 2D (2 dimensional) array in Python using NumPy library, we can use any of the following methods.

  • numpy.array() – Creates array from given values.
  • numpy.zeros() – Creates array of zeros.
  • numpy.ones() – Creates array of ones.
  • numpy.empty() – Creates an empty array.

1. Create 2D Array using numpy.array()

Pass a list of lists to numpy.array() function.

Python Program

import numpy as np

# Create a 2D array with shape (3, 4)
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

print(arr)
Run Code Copy

Output

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

2. Create 2D Array using numpy.zeros()

Pass shape of the required 2D array, as a tuple, as argument to numpy.zeros() function. The function returns a numpy array with specified shape, and all elements in the array initialised to zeros.

Python Program

import numpy as np

# Create a 2D array with shape (3, 4)
shape = (3, 4)
arr = np.zeros(shape)

print(arr)
Run Code Copy

Output

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

3. Create 2D Array using numpy.ones()

Pass shape of the required 2D array, as a tuple, as argument to numpy.ones() function. The function returns a numpy array with specified shape, and all elements in the array initialised to ones.

Python Program

import numpy as np

# Create a 2D array with shape (3, 4)
shape = (3, 4)
arr = np.ones(shape)

print(arr)
Run Code Copy

Output

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

4. Create 2D Array using numpy.empty()

Pass shape of the required 2D array, as a tuple, as argument to numpy.empty() function. The function returns a numpy array with specified shape.

Python Program

import numpy as np

# Create a 2D array with shape (3, 4)
shape = (3, 4)
arr = np.empty(shape)

print(arr)
Run Code Copy

Output

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

Summary

In this NumPy Tutorial, we learned how to create a 2D numpy array in Python using different NumPy functions.

Related Tutorials

Code copied to clipboard successfully 👍