logo

[pandas-basic] 참/거짓으로 선택

판다스에서 조건으로 행을 선택하는 또 다른 방법을 알아보겠습니다.

import pandas as pd
df = pd.read_excel('census.xlsx')
 

참/거짓으로 선택

판다스에서 다음과 같이 비교를 하면 age의 모든 값을 40과 비교하여 참(True), 거짓(False)의 시리즈를 만듭니다.

df['age'] > 40
0        False
1         True
2        False
         ...
32558     True
32559    False
32560     True
Name: age, Length: 32561, dtype: bool

참/거짓의 시리즈를 [] 사이에 넣어주면 해당 조건이 참인 행을 선택합니다.

df[df['age'] > 40]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
649Private1601879th5Married-spouse-absentOther-serviceNot-in-familyBlackFemale0016Jamaica<=50K
................................................
3255453Private321865Masters14Married-civ-spouseExec-managerialHusbandWhiteMale0040United-States>50K
3255858Private151910HS-grad9WidowedAdm-clericalUnmarriedWhiteFemale0040United-States<=50K
3256052Self-emp-inc287927HS-grad9Married-civ-spouseExec-managerialWifeWhiteFemale15024040United-States>50K

13443 rows × 15 columns

이 방법은 대체로 코드가 복잡하고, 실행 속도도 느립니다. 가능하면 query를 사용하세요.

 

and

두 조건 모두 참이어야 할 경우에는 & 연산자를 씁니다. 단, &==과 같은 비교연산자보다 계산 우선 순위가 높기 때문에 비교를 먼저 하도록 괄호를 씌워줍니다.

아래는 age가 40보다 크고, sexMale인 경우에만 참입니다.

(df['age'] > 40) & (df['sex'] == 'Male')
0        False
1         True
2        False
         ...
32558    False
32559    False
32560    False
Length: 32561, dtype: bool

아래는 age가 40보다 크고, sexMale인 행을 선택합니다.

df[(df['age'] > 40) & (df['sex'] == 'Male')]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
752Self-emp-not-inc209642HS-grad9Married-civ-spouseExec-managerialHusbandWhiteMale0045United-States>50K
................................................
3255043Self-emp-not-inc27242Some-college10Married-civ-spouseCraft-repairHusbandWhiteMale0050United-States<=50K
3255243Private84661Assoc-voc11Married-civ-spouseSalesHusbandWhiteMale0045United-States<=50K
3255453Private321865Masters14Married-civ-spouseExec-managerialHusbandWhiteMale0040United-States>50K

9497 rows × 15 columns

 

or

두 조건 중에 하나만 참이어도 되는 경우에는 |를 씁니다. |는 키보드에서 백스페이스와 엔터 사이의 긴 막대기 형태의 기호입니다. | 역시 ==과 같은 비교연산자보다 계산 우선 순위가 높기 때문에 비교를 먼저 하도록 괄호를 씌워줍니다.

아래는 relationshipHusband이거나 Wife인 경우에만 참입니다.

(df['relationship'] == 'Husband') | (df['relationship'] == 'Wife')
0        False
1         True
2        False
         ...
32558    False
32559    False
32560     True
Name: relationship, Length: 32561, dtype: bool

아래는 relationshipHusband이거나 Wife인 경우에만 참인 행을 선택합니다.

df[(df['relationship'] == 'Husband') | (df['relationship'] == 'Wife')]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
428Private338409Bachelors13Married-civ-spouseProf-specialtyWifeBlackFemale0040Cuba<=50K
................................................
3255627Private257302Assoc-acdm12Married-civ-spouseTech-supportWifeWhiteFemale0038United-States<=50K
3255740Private154374HS-grad9Married-civ-spouseMachine-op-inspctHusbandWhiteMale0040United-States>50K
3256052Self-emp-inc287927HS-grad9Married-civ-spouseExec-managerialWifeWhiteFemale15024040United-States>50K

14761 rows × 15 columns

 

not

반대되는 경우를 찾으려면 ~을 사용합니다. 아래는 age가 30보다 작고 raceBlack이 경우가 아닌 행를 찾습니다.

df[~((df['age'] < 30) & (df['race'] == "Black"))]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
039State-gov77516Bachelors13Never-marriedAdm-clericalNot-in-familyWhiteMale2174040United-States<=50K
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
238Private215646HS-grad9DivorcedHandlers-cleanersNot-in-familyWhiteMale0040United-States<=50K
................................................
3255858Private151910HS-grad9WidowedAdm-clericalUnmarriedWhiteFemale0040United-States<=50K
3255922Private201490HS-grad9Never-marriedAdm-clericalOwn-childWhiteMale0020United-States<=50K
3256052Self-emp-inc287927HS-grad9Married-civ-spouseExec-managerialWifeWhiteFemale15024040United-States>50K

31603 rows × 15 columns

 

포함 관계

포함관계를 확인할 때는 isin 메소드를 사용합니다.

아래는 relationshipHusband이거나 Wife에 포함될 때만 참입니다.

df['relationship'].isin(['Husband', 'Wife'])
0        False
1         True
2        False
         ...
32558    False
32559    False
32560     True
Name: relationship, Length: 32561, dtype: bool

아래는 relationshipHusband이거나 Wife에 포함되는 행만 선택합니다.

df[df['relationship'].isin(['Husband', 'Wife'])]
ageworkclassfnlwgteducationeducation_nummarital_statusoccupationrelationshipracesexcapital_gaincapital_losshours_per_weeknative_countryincome
150Self-emp-not-inc83311Bachelors13Married-civ-spouseExec-managerialHusbandWhiteMale0013United-States<=50K
353Private23472111th7Married-civ-spouseHandlers-cleanersHusbandBlackMale0040United-States<=50K
428Private338409Bachelors13Married-civ-spouseProf-specialtyWifeBlackFemale0040Cuba<=50K
................................................
3255627Private257302Assoc-acdm12Married-civ-spouseTech-supportWifeWhiteFemale0038United-States<=50K
3255740Private154374HS-grad9Married-civ-spouseMachine-op-inspctHusbandWhiteMale0040United-States>50K
3256052Self-emp-inc287927HS-grad9Married-civ-spouseExec-managerialWifeWhiteFemale15024040United-States>50K

14761 rows × 15 columns

Previous
조건 검색
Next
정렬