0. 주의사항 : 아래의 내용을 무조건적으로 신뢰하지 않기를 바란다. 프로그래밍의 세계는 매우 심오하고 복잡해서 지금 정리하는 내용이 완벽하다고 나조차도 신뢰하지 않기 때문이다.
1. 일자 : 2022년 1월 6일 14:00 ~ 18:00 (4일차)
2. 주제 : Pandas 실습
3. 내용
Pandas 실습 파일은 Kaggle의 Netflix Data를 이용하였다.
제시된 데이터를 토대로 문제를 해결하시오.
3.1. 넷플릭스 내 한국 작품은 얼마나 있는가?
조건 1. country column을 기준으로 한다.
조건 2. South Korea인 경우만 인정한다. (여러 국가가 합작한 경우는 인정하지 않는다)
해당 문제는 (1) groupby를 통해서 해결하는 방법과 (2) 데이터 필터링을 통해 해결하는 방법이 있다.
1번 문제와 2번 문제가 서로 비슷하기에
- 3.1번은 (2)을 이용해서 해결하는 과정을 기록하며
- 3.2번은 (1)을 이용해서 해결하는 방법을 기록한다.
나는 이 문제의 핵심은 "(제시된 국가)의 행 개수를 파악하는 것"이라고 생각하였다. 그러므로
(1) 제시된 데이터 중 "South Korea"라고 적힌 행만 출력한 이후
(2) 해당 데이터 프레임의 개수를 파악하는 방식으로 풀어보았다.
(1) 제시된 데이터 중 "South Korea"라고 적힌 행만 출력
데이터 행을 출력하기 이전, 먼저 read_csv를 사용하여 파일을 불러온다. 구체적인 원인은 잘 모르겠으나, csv파일을 불러오면서 \(역슬래시)를 그대로 사용하는 경우 간혹 경고가 뜨면서 거부되는 현상이 존재한다. 그러므로 \(역슬래시)는 /(슬래시)로 변경하도록 하자. 이후 head()와 tail()을 사용하여 데이터 상태를 간단히 체크하였다.
import pandas as pd
import numpy as np
# 경로 설정 시 \를 사용할 경우 오류를 반환하는 경우가 간혹 존재하므로
# /를 사용할 것을 권장한다.
netflix = pd.read_csv("D:/....(해당 파일이 있는 경로).../netflix_titles.csv")
# 데이터의 확인
# 맨 위와 맨 아래서부터 각각 5개씩 행을 출력한다.
netflix.head()
netflix.tail()
그다음 netflix['country']안에서 South Korea가 어떻게 사용되었는지 카테고리를 뽑아보았다.
netflix['country'].unique()
# <이하는 출력결과>
# array(['United States', 'South Africa', nan, 'India',
# 'United States, Ghana, Burkina Faso, United Kingdom, Germany, Ethiopia',
# 'United Kingdom', 'Germany, Czech Republic', 'Mexico', 'Turkey',
# 'Australia', 'United States, India, France', 'Finland',
# 'China, Canada, United States',
# 'South Africa, United States, Japan', 'Nigeria', 'Japan',
# 'Spain, United States', 'France', 'Belgium',
# 'United Kingdom, United States', 'United States, United Kingdom',
# 'France, United States', 'South Korea', 'Spain',
# 'United States, Singapore', 'United Kingdom, Australia, France',
# 'United Kingdom, Australia, France, United States',
# ...
# 'United States, East Germany, West Germany',
# 'France, Netherlands, South Africa, Finland',
# 'Egypt, Austria, United States', 'Russia, Spain',
# 'Croatia, Slovenia, Serbia, Montenegro', 'Japan, Canada',
# 'United States, France, South Korea, Indonesia',
# 'United Arab Emirates, Jordan'], dtype=object)
오류를 줄이기 위해서, 나는 출력된 카테고리 중에서 "South Korea'를 찾아 복사한 뒤 데이터 필터링을 진행하였다.
# 데이터 필터링을 통한 해결
netflix_korea = netflix[netflix['country'] == 'South Korea']
netflix_korea
# show_id type title director cast country date_added release_year rating duration listed_in description
# 104 s105 TV Show Tayo the Little Bus NaN Robyn Slade, Kami Desilets South Korea September 6, 2021 2016 TV-Y 2 Seasons Kids' TV, Korean TV Shows As they learn their routes around the busy cit...
# 124 s125 TV Show Pororo - The Little Penguin NaN NaN South Korea September 2, 2021 2013 TV-Y7 3 Seasons Kids' TV, Korean TV Shows On a tiny island, Pororo the penguin has fun a...
# 289 s290 TV Show The Crowned Clown NaN Yeo Jin-goo, Lee Se-young, Kim Sang-kyung, Jun... South Korea August 10, 2021 2019 TV-14 1 Season International TV Shows, Romantic TV Shows, TV ... Standing in for an unhinged Joseon king, a loo...
# 456 s457 TV Show Her Private Life NaN Park Min-young, Kim Jae-uk, Ahn Bo-hyun, Jung ... South Korea July 15, 2021 2019 TV-14 1 Season International TV Shows, Romantic TV Shows, TV ... An art curator's life unravels, as she tries t...
# 545 s546 TV Show YooHoo to the Rescue NaN Kira Buckland, Ryan Bartley, Bryce Papenbrook,... South Korea July 6, 2021 2020 TV-Y 3 Seasons Kids' TV, Korean TV Shows In a series of magical missions, quick-witted ...
# ... ... ... ... ... ... ... ... ... ... ... ... ...
# 8463 s8464 Movie The President's Barber Chan-sang Lim Kang-ho Song, So-ri Moon, Jae-eung Lee, Yeong-... South Korea October 1, 2017 2004 TV-MA 116 min Comedies, Dramas, International Movies The personal barber to the president, as well ...
# 8467 s8468 Movie The Prison Na Hyeon Suk-kyu Han, Rae-won Kim, Kyeong-yeong Lee, Wo... South Korea November 18, 2017 2017 TV-MA 125 min Action & Adventure, Dramas, International Movies A cop-turned-convict discovers a crime syndica...
# 8575 s8576 TV Show This Is My Love NaN Jin-mo Joo, Sa-rang Kim, Junior, Ja-in Lee, Su... South Korea May 22, 2017 2015 TV-14 1 Season International TV Shows, Korean TV Shows, Roman... A renowned actor who is still pining over the ...
# 8613 s8614 Movie Train to Busan Sang-ho Yeon Gong Yoo, Yu-mi Jung, Dong-seok Ma, Soo-an Kim... South Korea March 18, 2017 2016 TV-MA 118 min Action & Adventure, Horror Movies, Internation... As a zombie outbreak sweeps the country, a dad...
# 8684 s8685 TV Show Vroomiz NaN Joon-seok Song, Jeong-hwa Yang, Sang-hyun Um, ... South Korea August 1, 2017 2016 TV-Y 3 Seasons Kids' TV, Korean TV Shows For these half-car, half-animal friends, each ...
(2) 해당 데이터 프레임의 행 개수 파악
이후 나는 netflix_korea의 행 개수를 출력하여 한국 작품이 몇 개가 있는지를 찾아보았다.
len(netflix_korea)
# 출력결과 : 199
출력 결과 = 199이므로 netflix 내 한국 작품 개수는 총 199개임을 알 수 있다.
3.2. 넷플릭스에서 가장 많은 작품을 올린 국가는 어디이며, 해당 국가가 올린 작품의 총개수를 찾아라
조건 1. country column을 기준으로 한다.
조건 2. 단일 국가인 경우를 기준으로 결과를 구한다.
이 문제를 해결하기 위해서는 반드시 데이터 가공을 해주어야 한다. 먼저 결측치를 제거하여 빈 셀이 포함된 열을 삭제해주고, 이후 ,(콤마)가 포함된 값을 삭제해주는 것이다. 만약 데이터 전처리 및 가공과정을 진행하지 않을 경우, .max()를 통해서 가장 많은 작품을 올린 국가를 추출할 시 단일 국가가 아닌 형태가 출력되는 불상사가 생길 수 있다. 다행히 이번 과제에서는 이러한 부분까지 고려되지는 않으므로(전처리를 하기 전과 후의 결과가 동일하기 때문이다!) 데이터 전처리 단계를 거칠 필요는 없지만, 그래도 최대한 의도한 바를 따라가보도록 한다.
(1) 데이터의 전처리
데이터의 전처리는 (1) 결측치를 제거한 후 (2) ,(콤마)가 포함된 값을 삭제해주는 것을 말한다. (1)번 과정에서 유의해야 할 점은 netflix['country']에 존재하는 결측치 이외의 다른 결측치를 삭제하게 될 경우, 단일 국가의 콘텐츠 몇 개가 함께 삭제되어 정확한 값이 나오지 않을 수 있다. 그러므로 'country'에 해당하는 부분의 결측치만 제거해주도록 하자.
전처리 과정은 반드시 (1)와 (2)를 차례대로 거쳐야 하는데, (1)을 생략하고 (2)를 진행할 경우 오류가 발생하기 때문이다. 탐색공간 내 빈 셀이 존재해서 생기는 문제인 것으로 추측된다.
결측치는 dataframe_name.dropna("조건")을 사용하여 삭제하였다. 이번 과제에서 ("조건")에 사용된 내용은 subset, axis, inplace으로 각각 아래의 의미를 가지고 있다.
- subset = 삭제하고자 하는 결측치가 존재하는 열 지정
- axis = 0(행 전체 삭제), 1(열 전체 삭제)
- inplace = True(결측치 삭제 후 netflix에 다시 저장한다)
단일 국가가 아닌 행을 삭제할 때 사용한 함수는 .str.contains('부분일치로 검색할 문자열')이다. 아래 코드에서 사용자가 만약 netflix[netflix['country'].str.contains(',')]라고 입력하면 ,(콤마)가 포함된 셀만 남기게 된다. 그러나 netflix['country'].str.contains(',') 앞에 ~(부정)이 붙었으므로 ,(콤마)가 포함된 셀이 아닌 경우만 남은 것이다. 즉, 단일 국가만 필터링된 것이다.
# data가공
# 결측치 제거
# dataframe_name.isnull() = 결측치인 셀은 True, 나머지는 False를 출력
netflix.isnull()
netflix.dropna(subset = ['country'], axis = 0, inplace = True)
netflix
# ,가 포함된 값 제거
netflix = netflix[~ netflix['country'].str.contains(',')]
netflix
(2) groupby를 활용한 문제 해결
# groupby를 활용한 방식
# (1) Split
netflix_country = netflix['title'] .groupby(by = netflix['country'])
# (2) Apply and Combine
netflix_country_count = netflix_country.count()
netflix_country_count
# <이하는 출력결과>
# country
# Argentina 56
# Australia 87
# Austria 5
# Bangladesh 3
# Belarus 1
# ..
# Uruguay 3
# Venezuela 1
# Vietnam 7
# West Germany 1
# Zimbabwe 1
# Name: title, Length: 73, dtype: int64
여기서 사용자는 가장 "가장 많은 작품을 올린 국가"를 찾아야 한다. 그러므로 Series형태로 반환된 값 중 max()를 이용하여 "가장 많은 작품의 개수"를 찾는다. 우리가 'country'를 기준으로 groupby를 진행했기 때문에 자연스럽게 "가장 많은 작품을 올린 국가"도 알 수 있게 된다.
max_value = netflix_country_count.max()
netflix_country_count[netflix_country_count == max_value]
# <이하는 출력결과>
# country
# United States 2818
# Name: title, dtype: int64
따라서 가장 많은 작품을 올린 국가는 미국(United States)이며, 작품 수는 2818개이다.
'전문지식 함양 > TIL' 카테고리의 다른 글
[프로그래머스 겨울방학 인공지능 과정] 1주차 실습과제 (0) | 2022.01.09 |
---|---|
[프로그래머스 겨울방학 인공지능 과정] Matplotlib 기초 (0) | 2022.01.07 |
[프로그래머스 겨울방학 인공지능 과정] Pandas 기초 (0) | 2022.01.05 |
[프로그래머스 겨울방학 인공지능 과정] Numpy 기초와 선형대수 정리 (0) | 2022.01.04 |
[프로그래머스 겨울방학 인공지능 과정] 기초1. github와 jupyter note의 설치 (0) | 2022.01.04 |