[파이썬][numpy] numpy `zeros`와 `ones` 함수

In this blog post, we will explore the zeros and ones functions in the numpy library for Python. These functions are useful for creating arrays filled with either zeros or ones, respectively. They are often used as the initial array for further computations or as placeholders for data.

The zeros function

The zeros function in NumPy creates a new array of specified shape and fills it with zeros. The syntax for using the zeros function is as follows:

import numpy as np

# Create a 1-dimensional array of zeros
zeros_array = np.zeros(shape, dtype=float)

Here, shape is a tuple that describes the shape of the array, and dtype is an optional parameter that specifies the data type of the array elements. By default, the dtype is float.

Let’s look at a few examples to understand the usage of the zeros function:

import numpy as np

# Create a 1D array of zeros with 5 elements
zeros_array = np.zeros(5)
print(zeros_array)
# Output: [0. 0. 0. 0. 0.]

# Create a 2D array of zeros with shape (2, 3)
zeros_matrix = np.zeros((2, 3))
print(zeros_matrix)
# Output: [[0. 0. 0.]
#          [0. 0. 0.]]

The ones function

Similar to the zeros function, the ones function creates a new array of the specified shape, but this time it fills it with ones. The syntax for using the ones function is as follows:

import numpy as np

# Create a 1-dimensional array of ones
ones_array = np.ones(shape, dtype=float)

Here, shape and dtype have the same meanings as in the zeros function.

Let’s see some examples of using the ones function:

import numpy as np

# Create a 1D array of ones with 3 elements
ones_array = np.ones(3)
print(ones_array)
# Output: [1. 1. 1.]

# Create a 2D array of ones with shape (2, 4)
ones_matrix = np.ones((2, 4), dtype=int)
print(ones_matrix)
# Output: [[1 1 1 1]
#          [1 1 1 1]]

Conclusion

The zeros and ones functions in numpy provide a convenient way to create arrays filled with zeros or ones. By specifying the shape and data type, you can easily create arrays of various dimensions and with different data types. These functions are particularly useful when initializing arrays for further computations or when creating placeholders for data.