목록을 numpy 배열로 변환하는 방법(예제 포함)
다음 기본 구문을 사용하여 Python의 목록을 NumPy 배열로 변환할 수 있습니다.
import numpy as np my_list = [1, 2, 3, 4, 5] my_array = np. asarray (my_list)
다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.
예제 1: 목록을 NumPy 배열로 변환
다음 코드는 Python의 목록을 NumPy 배열로 변환하는 방법을 보여줍니다.
import numpy as np #create list of values my_list = [3, 4, 4, 5, 7, 8, 12, 14, 14, 16, 19] #convert list to NumPy array my_array = np. asarray (my_list) #view NumPy array print (my_array) [3 4 4 5 7 8 12 14 14 16 19] #view object type type (my_array) numpy.ndarray
변환 중에 dtype 인수를 사용하여 새 NumPy 배열에 대한 특정 데이터 유형을 지정할 수도 있습니다.
import numpy as np #create list of values my_list = [3, 4, 4, 5, 7, 8, 12, 14, 14, 16, 19] #convert list to NumPy array my_array = np. asarray (my_list, dtype= np.float64 ) #view data type of NumPy array print ( my_array.dtype ) float64
예제 2: 목록 목록을 NumPy 배열 배열로 변환
다음 코드는 목록 목록을 NumPy 배열 배열로 변환하는 방법을 보여줍니다.
import numpy as np #create list of lists my_list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] #convert list to NumPy array my_array = np. asarray (my_list_of_lists) #view NumPy array print (my_array) [[1 2 3] [4 5 6] [7 8 9]]
그런 다음 모양 함수를 사용하여 새 배열 배열의 크기를 빠르게 얻을 수 있습니다.
print ( my_array.shape )
(3, 3)
이는 NumPy 배열 배열에 3개의 행과 3개의 열이 있음을 알려줍니다.
추가 리소스
다음 튜토리얼에서는 Python에서 다른 일반적인 데이터 변환을 수행하는 방법을 설명합니다.
Python에서 목록을 DataFrame으로 변환하는 방법
인라인 List DataFrame을 Python으로 변환하는 방법
Pandas 시리즈를 DataFrame으로 변환하는 방법
Pandas 시리즈를 NumPy 배열로 변환하는 방법