2.Indexing, Selecting & Assigning
Introduction
작업할 DataFrame 또는 Series의 특정 값을 빠르고 효과적으로 선택하는 방법은 python으로 데이터 작업을 할 때 가장 먼저 배워야 할 사항이다.
Native accessors
네이티브 파이썬 개체는 데이터를 인덱싱하는 좋은 방법을 제공한다. pandas 또한 동일한 방법을 지원한다.
print(reviews)
파이썬에서 우리는 객체의 속성에 접근할 수 있다.
예를들어 책 객체는 제목 속성을 가질 수 있는데 우리는 이것을 book.title이라고 부르면서 접근 할 수 있다.
pandas의 dataFrame도 위와같이 작동한다.
print(reviews.country)
파이썬 딕셔너리에서 우리는 인덱싱 연산자인 []를 이용해서 값에 접근한다. DataFrame 또한 마찬가지다.
print(reviews['country'])
위에서 DataFrame에서 Series를 선택하는 2가지 방법을 살펴보았다.
두 방법의 큰 차이는 보이지 않지만 []연산자는 변수를 이용해서 보다 더 유연하게 인덱싱을 할 수 있다.
[]연산자를 한번더 사용하면 특정값을 드릴다운 할 수 있다.
print(reviews['country'][0])
Indexing in pandas
인덱싱 연산자와 속성 선택은 Python 생태계의 나머지 부분과 동일하게 작동하기 때문에 좋다. 초보자로서 그것들이 사용하기 쉽게 만들어 준다. 그러나 pandas는 roc와 iloc라는 고유한 접근자를 가지고 있다. 좀 더 발전된 작업을 하기 위해서는 roc와 iloc를 사용하여야 한다.
Index-based selection
pandas의 색인은 두가지 패러다임 중 하나에서 작동 한다. 첫 번째는 Index-based selection이다.
데이터 내 숫자 위치에 따라 데이터를 선택하는 것이다. iloc는 이 패러다임을 따른다.
print(reviews.iloc[0])
loc와 iloc는 모두 첫번째 행, 두번째 열이다. 이것은 우리가 네이티브 파이썬에서 하는 첫 번째 열,두번째 행과 반대이다.
즉 행을 검색하는것이 더 쉬워지고 열을 검색하는것이 조금 더 어려워 진다. iloc가 포함된 열을 가져오려면 다음을 수행할 수 있다.
print(reviews.iloc[:,0])
:연산자는 그 자체로 네이티브 파이썬처럼 모든 것을 의미한다. 하지만 다른 선택자와 결합해서 사용하면 값의 범위를 나타나는 데에 사용될 수 있다.
print(reviews.iloc[:3,0])
이것은 범위 또는 리스트로도 가능하다
print(reviews.iloc[1:3,0]) 1~3
print(reviews.iloc[[0,1,2],0])
마지막으로 음수는 선택에 사용될 수 있다. 음수를 사용하면 값의 끝에서 앞으로 카운트를 시작한다.
print(reviews.iloc[-5:])
Label-based selection
속성 선택의 두번째 패러다임은 label-based selection으로 loc연산자가 해당된다. 이 패러다임은 데이터의 위치가 아니라 인덱스 값으로 데이터를 찾는다.
print(reviews.loc[0,'country'])
iloc는 데이터 집합의 인덱스를 무시하기 때문에 개념적으로 loc보다 간단하다. iloc를 사용하면 데이터 집합을 위치별로 인덱싱해야 하는 큰 매트릭스처럼 취급한다.
반대로 loc는 인덱스 정보를 사용하여서 작업을 수행한다. 데이터 집합은 일반적으로 의미있는 인덱스를 가지고 있기 때문에, 대신 loc를 사용하여 작업을 수행하는 것이 더 쉽다.
print(reviews.loc[:, ['taster_name', 'taster_twitter_handle', 'points']])
Choosing between loc and iloc
loc와 iloc 사이에서 선택하거나 전환할 때 명심할 가치가 있는 한 가지 "gotcha"가 있는데 그것은 두 방법이 약간 다른 색인체계를 사용한다는 것이다.
iloc는 범위의 첫 번째 요소가 포함되고 마지막 요소가 제외되는 Python stdlib 인덱싱 체계를 사용한다.
loc[0:10] → 0~10
iloc[0:10] → 0~9
왜 두방식은 다를까? loc는 문자열 같은 stdlib 타입을 인덱싱 할 수 있다. 따라서 인덱싱을 할때 apple:potato는 applepotato를 가르키는 것이 applepotato 이전의 인덱스를 가르키는 것보다 더 편리하기 때문이다.
Manipulation the index
Lable based-index는 인덱스의 레이블에서 힘을 파생한다. 비판적으로 우리가 사용하는 지수는 불변성이 아니다. 우리가 적합하다고 생각하는 어떤 방식으로도 지수를 조작할 수 있다.
set_index()를 사용하여 작업을 수행할 수 있다.
print(reviews.set_index("title"))
이 기능은 데이터 집합에 대해 현재보다 나은 인덱스를 생성할 수 있는 경우 유용하다.
Conditional Selection
지금까지 DataFrame 자체의 구조적 속성을 사용하여 다양한 데이터 진보를 인덱싱 했습니다. 그러나 데이터로부터 흥미로운 것들을 하기 위해서는 종종 조건에 따라 질문을 해야한다.
예를 들어 우리가 이탈리아에서 생산되는 평균보다 더 좋은 와인에 특별히 관심이 있다고 가정해 보자.
print(reviews.country =='Italy')
이 연산은 각 기록의 국가를 기준으로 true/false 시리즈가 생성되었다. 그런 다음 이 결과를 loc 내부에서 사용하여 관련 데이터를 선택할 수 있다.
print(reviews.loc[reviews.country =='Italy'])
이 데이터 프레임은 원래 약 130000개의 데이터가 있엇고 현재 최대 20000개의 행이 있다. 이 말은 약 15%의 와인이 이탈리아에서 생성된다는것을 의미한다.
우리는 또한 어떤 와인이 평균보다 더 나은지 알고 싶다. 와인은 80~100점의 범위를 가지므로 평균이상은 적어도 90점이상의 와인이라고 볼 수 있다. 우리는 &로 두 질문을 연결할 수 있다.
print(reviews.loc[(reviews.country == 'Italy') & (reviews.points >= 90)])
만약 우리가 이탈리아산 와인을 사거나 평균 이상의 와인을 산다면 &가 아닌 |를 통해 질문을 연결한다.
pandas는 몇 가지 조건부 선택지가 내장되어 있다. 그중에서 두가지를 여기서 강조할 것이다.
첫번째는 isin이다. isin을 사용하면 값 목록에 있는 데이터를 선택할 수 있다. 예를 들어 이탈리아나 프랑스 와인만을 선택할 때 사용할 수 있다.
print(reviews.loc[reviews.country.isin(['Italy', 'France'])])
두번째는 isnull이다. isnull을 사용하면 비어 있거나 비어있지 않은 값을 강조 표시할 수 있다. 예를 들어 데이터 세트에서 가격표가 부족한 와인을 걸러내기 위해 다음과 같이 해야 한다
print(reviews.loc[reviews.price.notnull()])
Assigning data
반대로 데이터를 데이터 프레임에 할당하는 것은 쉽다. 상수 값을 할당할 수 있다.
reviews['critic'] = 'everyone'
reviews['critic']
Exercise
1.
Select the description
column from reviews
and assign the result to the variable desc
.
# Your code here
desc = ____
# Check your answer
q1.check()
//answer
desc = reviews.description
2.
Select the first value from the description column of reviews
, assigning it to variable
first_description = ____
# Check your answer
q2.check()
first_description
//answer
first_description = reviews.description[0]
3.
select the first row of data (the first record) from reviews
, assigning it to the variable first_row
.
first_row = ____
# Check your answer
q3.check()
first_row
//answer
first_row = reviews.loc[0]
4.
Select the first 10 values from the description
column in reviews
, assigning the result to variable first_descriptions
.
Hint: format your output as a pandas Series.
first_descriptions = ____
# Check your answer
q4.check()
first_descriptions
first_descriptions = reviews.description[:10]
5.
Select the records with index labels 1
, 2
, 3
, 5
, and 8
, assigning the result to the variable sample_reviews
.
In other words, generate the following DataFrame:
sample_reviews = ____
# Check your answer
q5.check()
sample_reviews
//anaswer
sample_reviews = reviews.iloc[[1, 2, 3, 5, 8], :]
6.
Create a variable df
containing the country
, province
, region_1
, and region_2
columns of the records with the index labels 0
, 1
, 10
, and 100
. In other words, generate the following DataFrame:
df = ____
# Check your answer
q6.check()
df
//answer
cols = ['country', 'province', 'region_1', 'region_2']
rows = [0, 1, 10, 100]
df = reviews.loc[rows, cols
7.
Create a variable df
containing the country
and variety
columns of the first 100 records.
Hint: you may use loc
or iloc
. When working on the answer this question and the several of the ones that follow, keep the following "gotcha" described in the tutorial:
iloc uses the Python stdlib indexing scheme, where the first element of the range is included and the last one excluded. loc, meanwhile, indexes inclusively.
This is particularly confusing when the DataFrame index is a simple numerical list, e.g. 0,...,1000. In this case df.iloc[0:1000] will return 1000 entries, while df.loc[0:1000] return 1001 of them! To get 1000 elements using loc, you will need to go one lower and ask for df.iloc[0:999].
df = ____
# Check your answer
q7.check()
df
df = reviews.loc[:99, ['country', 'variety']]
8.
Create a DataFrame italian_wines
containing reviews of wines made in Italy
. Hint: reviews.country
equals what?
italian_wines = ____
# Check your answer
q8.check()
//answer
italian_wines= reviews.loc[reviews.country == 'Italy']
9.
Create a DataFrame top_oceania_wines
containing all reviews with at least 95 points (out of 100) for wines from Australia or New Zealand.
top_oceania_wines = ____
# Check your answer
q9.check()
top_oceania_wines
top_oceania_wines= reviews.loc[(reviews.points >= 95) & (reviews.country.isin(['Australia', 'New Zealand']))]
'MachineLearning' 카테고리의 다른 글
[kaggle] Pandas Tutorial - 6 (0) | 2022.05.27 |
---|---|
[kaggle] Pandas Tutorial - 5 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 4 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 3 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 1 (0) | 2022.05.27 |