Using np.array(), np.zeros(), np.ones(), np.empty(), and np.full in NumPy Framework
NumPy provides several functions to create arrays with different values. This tutorial covers np.array()
, np.zeros()
, np.ones()
, np.empty()
, and np.full()
with examples.
1. Creating an Array Using np.array()
The np.array()
function is used to create arrays from Python lists.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr)
Output:
[1 2 3 4 5]
2. Creating an Array of Zeros Using np.zeros()
The np.zeros()
function creates an array filled with zeros.
zeros_array = np.zeros((3, 3)) print(zeros_array)
Output:
[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
3. Creating an Array of Ones Using np.ones()
The np.ones()
function creates an array filled with ones.
ones_array = np.ones((2, 4)) print(ones_array)
Output:
[[1. 1. 1. 1.] [1. 1. 1. 1.]]
4. Creating an Empty Array Using np.empty()
The np.empty()
function creates an uninitialized array, meaning it contains arbitrary values.
empty_array = np.empty((2, 3)) print(empty_array)
Output: (Values may vary)
[[4.67296746e-307 1.69121096e-306 1.33511562e-306] [2.22507386e-307 1.33511969e-306 3.56043056e-307]]
5. Creating an Array with a Constant Value Using np.full()
The np.full()
function creates an array filled with a specified constant value.
full_array = np.full((3, 3), 7) print(full_array)
Output:
[[7 7 7] [7 7 7] [7 7 7]]
Conclusion
NumPy provides various functions to create arrays efficiently. Understanding these functions helps in handling numerical data effectively.