Pandas: dataframe을 열 값으로 분할하는 방법
다음 기본 구문을 사용하여 Pandas DataFrame을 열 값으로 분할할 수 있습니다.
#define value to split on x = 20 #define df1 as DataFrame where 'column_name' is >= 20 df1 = df[df[' column_name '] >= x] #define df2 as DataFrame where 'column_name' is < 20 df2 = df[df[' column_name '] < x]
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Pandas DataFrame을 열 값으로 분할
다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ' points ': [22, 24, 19, 18, 14, 29, 31, 16], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print (df) team points rebounds 0 to 22 11 1 B 24 8 2 C 19 10 3 D 18 6 4 E 14 6 5 F 29 5 6 G 31 9 7:16:12
다음 코드를 사용하여 DataFrame을 두 개의 DataFrame으로 분할할 수 있습니다. 여기서 첫 번째는 “포인트”가 20보다 크거나 같은 행을 포함하고 두 번째는 “포인트”가 20보다 작은 행을 포함합니다.
#define value to split on x = 20 #define df1 as DataFrame where 'points' is >= 20 df1 = df[df[' points '] >= x] print (df1) team points rebounds 0 to 22 11 1 B 24 8 5 F 29 5 6 G 31 9 #define df2 as DataFrame where 'points' is < 20 df2 = df[df[' points '] < x] print (df2) team points rebounds 2 C 19 10 3 D 18 6 4 E 14 6 7:16:12
Reset_index() 함수를 사용하여 각 결과 DataFrame에 대한 인덱스 값을 재설정할 수도 있습니다.
#define value to split on x = 20 #define df1 as DataFrame where 'points' is >= 20 df1 = df[df[' points '] >= x]. reset_index (drop= True ) print (df1) team points rebounds 0 to 22 11 1 B 24 8 2 F 29 5 3 G 31 9 #define df2 as DataFrame where 'points' is < 20 df2 = df[df[' points '] < x]. reset_index (drop= True ) print (df2) team points rebounds 0 C 19 10 1 D 18 6 2 E 14 6 3:16:12
각 결과 DataFrame의 인덱스는 이제 0에서 시작합니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
Pandas에서 KeyError를 수정하는 방법
해결 방법: ValueError: float NaN을 int로 변환할 수 없습니다.
해결 방법: ValueError: 피연산자를 모양과 함께 브로드캐스트할 수 없습니다.