Create new ndarray
Here are a few ways to create a new NumPy array (ndarray) in Python:
Method 1: Using the numpy.array()
function
import numpy as np
arr = np.array([1, 2, 3, 4, 5]) # create an array from a list
print(arr) # [1 2 3 4 5]
Method 2: Using the numpy.zeros()
function
import numpy as np
arr = np.zeros((3, 4)) # create a 3x4 array filled with zeros
print(arr) # [[0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]]
Method 3: Using the numpy.ones()
function
import numpy as np
arr = np.ones((2, 3)) # create a 2x3 array filled with ones
print(arr) # [[1. 1. 1.]
# [1. 1. 1.]]
Method 4: Using the numpy.full()
function
import numpy as np
arr = np.full((2, 3), 5) # create a 2x3 array filled with 5
print(arr) # [[5. 5. 5.]
# [5. 5. 5.]]
Method 5: Using the numpy.random.rand()
function
import numpy as np
arr = np.random.rand(2, 3) # create a 2x3 array with random values between 0 and 1
print(arr) # [[0.4321 0.8123 0.2198]
# [0.6543 0.1234 0.9876]]
These are just a few examples of how you can create a new NumPy array. There are many other ways to create arrays, depending on your specific use case.