Pandas 시리즈를 numpy 배열로 변환하는 방법(예제 포함)
다음 구문을 사용하여 pandas 시리즈를 NumPy 배열로 변환할 수 있습니다.
seriesName. to_numpy ()
다음 예에서는 이 구문을 실제로 사용하는 방법을 보여줍니다.
예 1: 시리즈를 NumPy 배열로 변환
다음 코드는 pandas 시리즈를 NumPy 배열로 변환하는 방법을 보여줍니다.
import pandas as pd import numpy as np #define series x = pd. Series ([1, 2, 5, 6, 9, 12, 15]) #convert series to NumPy array new_array = x. to_numpy () #view NumPy array new_array array([ 1, 2, 5, 6, 9, 12, 15]) #confirm data type type(new_array) numpy.ndarray
type() 함수를 사용하여 pandas 시리즈가 NumPy 배열로 변환되었는지 확인합니다.
예시 2: DataFrame 열을 NumPy 배열로 변환
다음 코드는 pandas DataFrame의 열을 NumPy 배열로 변환하는 방법을 보여줍니다.
import pandas as pd import numpy as np #define DataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #convert 'points' column to NumPy array new_array = df[' points ']. to_numpy () #view NumPy array new_array array([25, 12, 15, 14, 19, 23, 25, 29]) #confirm data type type(new_array) numpy.ndarray
dtype()을 사용하여 새 NumPy 배열의 데이터 유형을 확인할 수도 있습니다.
#check datatype new_array. dtype dtype('int64')
새로운 NumPy 배열이 정수임을 알 수 있습니다.
추가 리소스
Pandas DataFrame을 NumPy 배열로 변환하는 방법
Pandas DataFrame을 목록으로 변환하는 방법
사전을 Pandas DataFrame으로 변환하는 방법