Series에 조건식을 적용하여 각 행이 참, 거짓인지 구분하는 bool series를 만든다. 이를 df에 대입하면 이 조건들만 만족하는 행들만 선택할 수 있다.
import seaborn as sns
titanic = sns.load_dataset('titanic')
# 나이가 10대인 승객을 뽑아보자
mask1 = (titanic.age >= 10) & (titanic.age < 20)
df_teenage = titanic.loc[mask1, :]
print(df_teenage.head())
<class 'pandas.core.series.Series'>
survived pclass ... alive alone
9 1 2 ... yes False
14 0 3 ... no True
22 1 3 ... yes True
27 0 1 ... no False
38 0 3 ... no False
[5 rows x 15 columns]
이번에는 나이가 10세 미만인 여성 승객을 선택해보자.
import seaborn as sns
titanic = sns.load_dataset('titanic')
# 나이가 10대인 승객을 뽑아보자
mask1 = (titanic.age >= 10) & (titanic.age < 20)
df_teenage = titanic.loc[mask1, :]
print(df_teenage.head())
print('\\n\\n')
# 나이가 10세 미만인 여성 승객을 선택해보자.
mask2 = (titanic['sex'] == 'female') & (titanic['age'] < 10)
df_female_under10 = titanic[mask2]
print(df_female_under10.head())
survived pclass ... alive alone
9 1 2 ... yes False
14 0 3 ... no True
22 1 3 ... yes True
27 0 1 ... no False
38 0 3 ... no False
[5 rows x 15 columns]
survived pclass ... alive alone
10 1 3 ... yes False
24 0 3 ... no False
43 1 2 ... yes False
58 1 2 ... yes False
119 0 3 ... no False
[5 rows x 15 columns]
isin() 메서드를 적용하면 특정 값을 가진 행들을 따로 추출할 수 있다. 이때 isin() 메소드에 DF의 열에서 추출하려는 값들로 만든 리스트를 전달한다.
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')
pd.set_option('display.max_columns', 10)
# sibsp : 탑승한 형제 또는 배우자의 수
mask3 = titanic['sibsp'] == 3
mask4 = titanic['sibsp'] == 4
mask5 = titanic['sibsp'] == 5
df_boolean = titanic[mask3 | mask4 | mask5]
print(df_boolean.head())
print()
# sibsp이 3, 4, 5안에 있는 행만 선택
isin_filter = titanic['sibsp'].isin([3, 4, 5])
df_isin = titanic[isin_filter]
print(df_isin.head())
survived pclass sex age sibsp ... adult_male deck embark_town \\
7 0 3 male 2.0 3 ... False NaN Southampton
16 0 3 male 2.0 4 ... False NaN Queenstown
24 0 3 female 8.0 3 ... False NaN Southampton
27 0 1 male 19.0 3 ...
True C Southampton
50 0 3 male 7.0 4 ... False NaN Southampton
alive alone
7 no False
16 no False
24 no False
27 no False
50 no False
[5 rows x 15 columns]
survived pclass sex age sibsp ... adult_male deck embark_town \\
7 0 3 male 2.0 3 ... False NaN Southampton
16 0 3 male 2.0 4 ... False NaN Queenstown
24 0 3 female 8.0 3 ... False NaN Southampton
27 0 1 male 19.0 3 ...
True C Southampton
50 0 3 male 7.0 4 ... False NaN Southampton
alive alone
7 no False
16 no False
24 no False
27 no False
50 no False
[5 rows x 15 columns]