Pandas에서 특정 열을 보존하는 방법(예제 포함)
다음 방법을 사용하여 Pandas DataFrame의 특정 열만 유지할 수 있습니다.
방법 1: 유지할 열 지정
#only keep columns 'col1' and 'col2' df[[' col1 ', ' col2 ']]
방법 2: 삭제할 열 지정
#drop columns 'col3' and 'col4' df[df. columns [~df. columns . isin ([' col3 ',' col4 '])]]
다음 예에서는 다음 Pandas DataFrame에서 각 메서드를 사용하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B'], ' points ': [11, 7, 8, 10, 13, 13], ' assists ': [5, 7, 7, 9, 12, 9], ' rebounds ': [11, 8, 10, 6, 6, 5]}) #view DataFrame df team points assists rebounds 0 A 11 5 11 1 To 7 7 8 2 to 8 7 10 3 B 10 9 6 4 B 13 12 6 5 B 13 9 5
방법 1: 유지할 열 지정
다음 코드는 “팀” 및 “포인트” 열만 유지하는 새 DataFrame을 정의하는 방법을 보여줍니다.
#create new DataFrame and only keep 'team' and 'points' columns
df2 = df[[' team ', ' points ']]
#view new DataFrame
df2
team points
0 to 11
1 to 7
2 to 8
3 B 10
4 B 13
5 B 13
결과 DataFrame에는 우리가 지정한 두 개의 열만 유지됩니다.
방법 2: 삭제할 열 지정
다음 코드는 원래 DataFrame에서 “참석” 및 “반송” 열을 제거하는 새 DataFrame을 정의하는 방법을 보여줍니다.
#create new DataFrame and that drops 'assists' and 'rebounds'
df2 = df[df. columns [~df. columns . isin ([' assists ', ' rebounds '])]]
#view new DataFrame
df2
team points
0 to 11
1 to 7
2 to 8
3 B 10
4 B 13
5 B 13
결과 DataFrame은 원래 DataFrame에서 “지원” 및 “반송” 열을 제거하고 나머지 열은 유지합니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas DataFrame에서 첫 번째 열을 제거하는 방법
Pandas에서 중복 열을 제거하는 방법
Pandas에서 인덱스별로 열을 삭제하는 방법