[파이썬][numpy] numpy 배열 생성

In the world of data science and numerical computing, the numpy library in Python plays a vital role. Numpy provides a powerful and efficient way to create and manipulate arrays of homogeneous data.

In this blog post, we will explore the various ways to create numpy arrays using Python.

1. Creating an Array from a List

The simplest way to create a numpy array is by converting a list into an array using the numpy.array() function. Here’s an example:

import numpy as np

my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)

print(my_array)

Output:

[1 2 3 4 5]

In this example, we import the numpy library using the alias np for simplicity. We create a list my_list and then convert it into a numpy array using the numpy.array() function. Finally, we print the resulting numpy array.

2. Creating an Array with Explicit Values

If you want to create a numpy array with explicit values, you can use the numpy.array() function with a list of values provided directly as an argument. Here’s an example:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5])

print(my_array)

Output:

[1 2 3 4 5]

In this example, we pass [1, 2, 3, 4, 5] directly to the numpy.array() function to create a numpy array.

3. Creating an Array with Zeros or Ones

Sometimes, you may need to create an array filled with either zeros or ones. Numpy provides dedicated functions - numpy.zeros() and numpy.ones() - for this purpose. Here are some examples:

import numpy as np

zeros_array = np.zeros((3, 4))
ones_array = np.ones((2, 2))

print(zeros_array)
print(ones_array)

Output:

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

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

In this example, we use numpy.zeros() to create a 3x4 array filled with zeros and numpy.ones() to create a 2x2 array filled with ones. The argument passed to these functions is a tuple specifying the shape of the resulting array.

4. Creating an Array with a Range of Values

Numpy provides the numpy.arange() function to create an array with a range of values. This function is similar to the built-in range() function of Python, but it returns a numpy array instead. Here’s an example:

import numpy as np

range_array = np.arange(1, 10, 2)

print(range_array)

Output:

[1 3 5 7 9]

In this example, we use numpy.arange() to create a numpy array with values from 1 to 10 (exclusive) with a step of 2.

These are just a few examples of how to create numpy arrays in Python. Numpy provides many more functions and methods to create arrays with different shapes and initialization values.

Numpy arrays are incredibly powerful when it comes to mathematical operations, data manipulation, and scientific computations. They offer significant performance improvements compared to regular Python lists, making numpy a go-to library for data scientists and engineers.