Tech With Tim Logo
Go back

Array Creation

Array Creation

In the previous tutorial we learned how to create arrays based off of lists in python. In this tutorial you will learn how to use some of the numpy functions to create arrays in different ways.

To create an array filled completely with zeros we can use np.zeros(shape).

arr = np.zeros((2,3))

print(arr) 
# Prints array([[0., 0., 0.],
#               [0., 0., 0.])

Similarity we can use np.ones(shape).

arr = np.ones((2,3))

print(arr) 
# Prints array([[1., 1., 1.],
#               [1., 1., 1.])

Another useful function is np.arange().

arr = np.arange(10)
print(arr) 
# Prints array([0,1,2,3,4,5,6,7,8,9])

arr = np.arange(4, 10, 2)
print(arr)
# Prints array([4,6,8])

arr = np.arange(0,1,0.1)
print(arr)
# Prints array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

We can also use .linspace(start, stop, values) in a similar way to .arange().

arr = np.linspace(1, 3, 6)
print(arr) # -> array([1. , 1.4, 1.8, 2.2, 2.6, 3. ])

# the linspace function will automatically calculate the step value
# based on the number of elements we specify

We can also create an array full of a constant value using np.full(shape, value).

arr = np.full((2,2),8)
print(arr)  # -> array([[8, 8],
#                       [8, 8]])

To create an identity matrix we can use np.eye(size).

arr = np.eye(3)
print(arr) # -> array([[1., 0., 0.],
#                      [0., 1., 0.],
#                      [0., 0., 1.]])

To create a random array of floats we can use np.random.random(size).

arr = np.random.random((2,2))
print(arr) # ->array([[0.65208707,0.02997459],
#                     [0.05827481, 0.34312981]])

Dtype

When creating arrays we sometimes have the option to specify their data type using the argument dtype=, like so:

arr = np.ones((3,3), dtype=int)

arr = np.zeros((2,2), dtype=str)
Design & Development by Ibezio Logo