[pandas] pandas 기초(3)
데이터 프레임(DataFrame)의 특정 행(row)과 열(column)을 선택하는 방법?
import pandas as pd
titanic = pd.read_csv('https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv')
titanic.head()
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S | 
| 1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S | 
| 3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S | 
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S | 
1. 데이터프레임의 특정 열(column)을 선택
- 열의 이름과 대괄호([])를 사용
age = titanic['Age'] # 하나의 열(column)은 Series 
age.head(3)
#print(type(age_name)) # Series
#age_name.dtype # float64
0    22.0
1    38.0
2    26.0
Name: Age, dtype: float64
age.shape # (891, ) -> (행, 열)
(891,)
- 여러 열을 선택
age_gender = titanic[['Age', 'Sex']]
temp = age_gender.head(3)
#temp.index = ['one', 'two', 'three'] #행(row)의 이름 변경
temp
| Age | Sex | |
|---|---|---|
| 0 | 22.0 | male | 
| 1 | 38.0 | female | 
| 2 | 26.0 | female | 
2. 데이터프레임의 특정 행(row)을 선택
- 조건식을 기반으로 행을 선택
- >,- ==,- !=,- <,- <=,- Series의 결과 값이 True or False
temp = titanic[ (titanic['Age'] > 35) ]
#temp = titanic[ (titanic['Age'] > 35) == True ]
temp.head(3)
#count = 0
#for i in titanic['Age'] > 35 :
#  if i == True :
#    count += 1
#print(count)
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 
| 6 | 7 | 0 | 1 | McCarthy, Mr. Timothy J | male | 54.0 | 0 | 0 | 17463 | 51.8625 | E46 | S | 
| 11 | 12 | 1 | 1 | Bonnell, Miss. Elizabeth | female | 58.0 | 0 | 0 | 113783 | 26.5500 | C103 | S | 
temp.shape
(217, 12)
- isin() 메소드 : Series 메소드, 하나 이상의 열에 원하는 값이 있는 행을 선택
pClass23 = titanic[ titanic['Pclass'].isin([2,3]) ]
pClass23.head()
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S | 
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S | 
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S | 
| 5 | 6 | 0 | 3 | Moran, Mr. James | male | NaN | 0 | 0 | 330877 | 8.4583 | NaN | Q | 
| 7 | 8 | 0 | 3 | Palsson, Master. Gosta Leonard | male | 2.0 | 3 | 1 | 349909 | 21.0750 | NaN | S | 
pClass23 = titanic[ (titanic['Pclass'] == 2) | (titanic['Pclass'] == 3)  ] # and(&), or(|)
pClass23.head()
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S | 
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S | 
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S | 
| 5 | 6 | 0 | 3 | Moran, Mr. James | male | NaN | 0 | 0 | 330877 | 8.4583 | NaN | Q | 
| 7 | 8 | 0 | 3 | Palsson, Master. Gosta Leonard | male | 2.0 | 3 | 1 | 349909 | 21.0750 | NaN | S | 
- notna() 메소드 : Series 메소드, 기존의 값(누락되지 않은)을 검색
- 결측값(missing value) : 값이 없는 경우
- NA(not available) : 누락 또는 사용할 수 없음. NaN, None 모두 포함.
- NaN(not a number) : 숫자 형태의 누락된 데이터
- None : 파이썬에서 누락된 데이터를 표현
#titanic['Age'].notna()
temp = titanic[titanic['Age'].notna()]
#titanic[(titanic['Age'].notna() == False)]
temp.head(3)
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S | 
| 1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 
| 2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S | 
temp.shape
(714, 12)
3. 데이터프레임의 특정 행과 열을 선택
- loc() : 행 또는 컬럼의 이름이나 boolean 값을 사용.
- iloc(): 행이나 컬럼의 인덱스 값을 사용.
#titanic.loc[0:5, ['Name', 'Age']]
titanic.loc[ titanic['Age'] > 35, 'Name'] 
#titanic.loc[ titanic['Age'] > 35, ['Name']] 
#titanic.loc[ titanic['Age'] > 35, ['Name', 'Age']]  
1      Cumings, Mrs. John Bradley (Florence Briggs Th...
6                                McCarthy, Mr. Timothy J
11                              Bonnell, Miss. Elizabeth
13                           Andersson, Mr. Anders Johan
15                      Hewlett, Mrs. (Mary D Kingcome) 
                             ...                        
865                             Bystrom, Mrs. (Karolina)
871     Beckwith, Mrs. Richard Leonard (Sallie Monypeny)
873                          Vander Cruyssen, Mr. Victor
879        Potter, Mrs. Thomas Jr (Lily Alexenia Wilson)
885                 Rice, Mrs. William (Margaret Norton)
Name: Name, Length: 217, dtype: object
#titanic.loc[0:5, 2:4] # 에러
titanic.iloc[0:5, 1:4]
#titanic.iloc[0:5, [1,3,8]]
| Survived | Pclass | Name | |
|---|---|---|---|
| 0 | 0 | 3 | Braund, Mr. Owen Harris | 
| 1 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | 
| 2 | 1 | 3 | Heikkinen, Miss. Laina | 
| 3 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | 
| 4 | 0 | 3 | Allen, Mr. William Henry | 
titanic.iloc[0:3, 3] = "anonymous"
titanic.head()
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | 3 | anonymous | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S | 
| 1 | 2 | 1 | 1 | anonymous | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C | 
| 2 | 3 | 1 | 3 | anonymous | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S | 
| 3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S | 
| 4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S | 
4. 정리
- 데이터의 하위 집합을 선택할 때, 대괄호([])를 사용.
- 이 대괄호 안에 단일 열/행 레이블, 목록을 사용.
- 열/행 레이블, 레이블 조각, 조건식 또는 콜론.
- loc/iloc를 이용하여 새로운 값을 입력할 수 있음.
 
      
댓글남기기