1. Native accessors
Python 객체에 indexing을 통해 값을 검색할 수 있지만, 판다스 라이브러리는 좀 더 쉬운 method를 제공한다.
# View all data
reviews
# View Series value from specific column
reviews.country
reviews['country']
# View value from specific columns and rows acting like dictionary
reviews['country'][0]
2. Indexing in pandas
판다스는 loc와 iloc라는 접근 연산자를 가지고 있다.
2.1 Index-based selection
판다스는 두가지 형태의 인덱스를 수행할 수 있다. 첫번째는 숫자 인덱스 기반 선택이다
# index-based selection
reviews.iloc[0]
reviews.iloc[:, 0]
loc와 iloc 둘다 행을 첫번째로 열을 두번째로 입력하여 데이터를 검색한다. Python의 경우 열을 먼저 선택한 후 행을 검색하게 된다.
2.2 Label-based selection
loc 연산자에 의한 데이터 검색방법은 label-based 선택이다. 이는 숫자 인덱스에 기반하지 않고 인덱스 값에 대하여 검색을 진행한다.
reviews.loc[0, 'country']
reviews.loc[:, ['taster_name', 'taster_twitter_handle', 'points']]
iloc는 개념적으로는 loc보다 훨씬 간단한데, 데이터셋을 하나의 거대한 행렬로써 바라보기 때문이다. 반대로 loc의 경우 색인을 통해 데이터를 검색한다.
3. Manipulating the index
라벨기반 선택은 라벨을 직접 선택하는데에 있어 강점이 존재한다. 데이터프레임의 인덱스를 변경할 순 없지만, 다른 열을 인덱스로 맞출 수는 있다.
Label-based selection derives its power from the labels in the index. Critically, the index we use is not immutable. We can manipulate the index in any way we see fit
# method set_index() : can access data into index
reviews.set_index('title')
4. Conditional selection
reviews.country == 'Italy'
위의 연산은 'True/False'값을 가지는 시리즈를 생성하게 된다. 이 시리즈를 데이터프레임에 []를 씌워주게 된다면, 조건에 맞는 데이터프레임을 검색할 수 있다.
reviews[reviews.country == 'Italy']
reviews.loc[reviews.country == 'Italy']
revies.loc[(reviews.country == 'Italy') & (revies.points >= 90)]
논리 연산자를 통해 좀 더 세부적인 조건을 만족하는 데이터셋을 추출할 수 있다.
4.1 isin
isin 메소드는 리스트의 값이 존재하는 데이터셋의 행을 추출한다.
reviews.loc[reviews.country.isin(['Italy', 'France'])]
isnull() 혹은 notnull()은 결측값이 존재하거나 존재하지 않는 데이터셋을 추출한다.
reviews.loc[reviews.price.notnull()]
5. Assigining data
데이터 값을 새로 할당하는 방법은 파이썬의 리스트 할당과 동일하게 코드를 작성하면 된다.
reviews['critic'] = 'everyone'
Source of the course : [Kaggle Course _ Indexing, Selecting & Assigning]
'Course > [Kaggle] Data Science' 카테고리의 다른 글
[Python] Grouping and Sorting (0) | 2022.02.11 |
---|---|
[Python] Summary Functions and Maps (0) | 2022.02.11 |
[Python] Creating, Reading and Writing (0) | 2022.02.11 |
[Python] Working with External Libraries (0) | 2022.02.11 |
[Python] Strings and Dictionaries (0) | 2022.02.11 |