소개
이 프로젝트에서는 Python 을 사용하여 COVID-19 데이터를 분석하는 방법을 배우게 됩니다. COVID-19 팬데믹은 전 세계에 큰 영향을 미쳤으며, 바이러스 확산을 추적하고 정보에 입각한 결정을 내리기 위해서는 데이터 이해가 필수적입니다.
👀 미리보기
{
"Confirmed": {
"Africa": 1203094,
"America": 6396173,
"Asia": 6480321,
"Europe": 3450299,
"Oceania": 27346,
"Others": 721,
"Total": 17557954
},
"Deaths": {
"Africa": 28289,
"America": 254610,
"Asia": 133186,
"Europe": 206438,
"Oceania": 576,
"Others": 15,
"Total": 623114
},
"Recovered": {
"Africa": 930536,
"America": 5087347,
"Asia": 5163062,
"Europe": 1927545,
"Oceania": 21892,
"Others": 651,
"Total": 13131033
},
"Active": {
"Africa": 244269,
"America": 1054216,
"Asia": 1184073,
"Europe": 1316316,
"Oceania": 4878,
"Others": 55,
"Total": 3803807
}
}
🎯 과제
이 프로젝트에서는 다음을 배우게 됩니다:
- 개발 환경을 설정하고 필요한 Python 라이브러리를 설치하는 방법
- COVID-19 데이터의 구조와 내용을 이해하는 방법
- 국가 이름을 대륙 이름으로 변환하는 함수를 구현하는 방법
- COVID-19 데이터를 처리하고 각 대륙별 요약 통계를 계산하는 방법
- 코드를 테스트하고 출력을 확인하는 방법
🏆 성과
이 프로젝트를 완료하면 다음을 수행할 수 있습니다:
- Python 에서 CSV 데이터를 사용하는 방법을 이해합니다.
- 데이터를 처리하고 분석하는 함수를 구현합니다.
- 데이터를 다른 형식 (예: CSV to JSON) 으로 변환합니다.
- 데이터 분석 및 시각화 경험을 얻습니다.
- 데이터 기반 통찰력을 통해 COVID-19 팬데믹에 대한 이해에 기여합니다.
환경 준비
이 단계에서는 COVID-19 데이터 분석 프로젝트를 위한 환경을 설정하는 방법을 배우게 됩니다.
- 터미널을 열고
/home/labex/project디렉토리로 이동합니다. - 다음 명령을 실행하여 필요한 Python 라이브러리를 설치합니다:
python3 -m pip install pandas country-converter
이렇게 하면 프로젝트에 필요한 pandas 및 country-converter 라이브러리가 설치됩니다.
데이터 이해
COVID-19 데이터는 /home/labex/project 디렉토리에 있는 CSV 파일로 제공됩니다. 이 파일에는 다음과 같은 열이 포함되어 있습니다:
Country_Region: 국가 또는 지역의 이름입니다.Confirmed: 확진된 COVID-19 사례의 총 수입니다.Deaths: COVID-19 사망자의 총 수입니다.Recovered: COVID-19 회복자의 총 수입니다.Active: 활성 COVID-19 사례의 총 수입니다.
귀하의 과제는 이 데이터를 처리하고 각 대륙별 요약 통계를 계산하는 것입니다.
country_to_continent 함수 구현
첫 번째 단계는 국가 이름을 해당 대륙 이름으로 변환할 수 있는 함수를 만드는 것입니다. /home/labex/project 디렉토리에 covid.py라는 새 파일을 만들고 다음 코드를 추가합니다:
import country_converter as coco
def country_to_continent(country_name):
"""This function takes a country name and returns the continent name."""
try:
## Convert country name to continent name
if country_name == "Diamond Princess" or country_name == "MS Zaandam":
return "Others"
country_continent_name = coco.convert(names=country_name, to="continent")
## If country name is not found, return 'Others'
if country_continent_name == "not found":
return "Others"
return country_continent_name
except:
return "Others"
이 함수는 country-converter 라이브러리를 사용하여 국가 이름을 해당 대륙 이름으로 변환합니다. 국가 이름을 찾을 수 없는 경우 "Others"를 반환합니다.
count 함수 구현
다음으로, COVID-19 데이터를 처리하고 각 대륙별 요약 통계를 반환하는 count 함수를 구현해야 합니다. covid.py 파일에 다음 코드를 추가합니다:
import json
import pandas as pd
def count(data):
"""This function takes a file path and returns the total number of
confirmed, deaths, recovered and active cases for each continent."""
## Read the data from the file
df = pd.read_csv(data)
## Fill missing values with 0
df.fillna(0, inplace=True)
## Remove rows with missing values
df = df[df["Confirmed"] == df["Deaths"] + df["Recovered"] + df["Active"]]
## Convert country name to continent name
df["Continent"] = df["Country_Region"].apply(country_to_continent)
## Convert data type to int
df[["Confirmed", "Deaths", "Recovered", "Active"]] = df[
["Confirmed", "Deaths", "Recovered", "Active"]
].astype(int)
## Select columns of interest and change them into dictionary
df = df[["Continent", "Confirmed", "Deaths", "Recovered", "Active"]]
result = df.groupby("Continent").sum().to_dict()
## Add total for each continent
for key in result.keys():
result[key]["Total"] = sum(result[key].values())
return json.dumps(result)
이 함수는 CSV 파일에서 COVID-19 데이터를 읽고, 데이터를 처리한 다음, 각 대륙별 요약 통계를 JSON 형식으로 반환합니다.
코드 테스트
코드를 테스트하려면 터미널에서 다음 명령을 실행할 수 있습니다:
python3 covid.py
이렇게 하면 count 함수가 실행되고 결과 JSON 데이터가 콘솔에 출력됩니다.
출력 결과 검증
count 함수의 출력은 다음과 유사한 JSON 문자열이어야 합니다:
{
"Confirmed": {
"Africa": 1203094,
"America": 6396173,
"Asia": 6480321,
"Europe": 3450299,
"Oceania": 27346,
"Others": 721,
"Total": 17557954
},
"Deaths": {
"Africa": 28289,
"America": 254610,
"Asia": 133186,
"Europe": 206438,
"Oceania": 576,
"Others": 15,
"Total": 623114
},
"Recovered": {
"Africa": 930536,
"America": 5087347,
"Asia": 5163062,
"Europe": 1927545,
"Oceania": 21892,
"Others": 651,
"Total": 13131033
},
"Active": {
"Africa": 244269,
"America": 1054216,
"Asia": 1184073,
"Europe": 1316316,
"Oceania": 4878,
"Others": 55,
"Total": 3803807
}
}
이 출력은 각 대륙별 요약 통계를 나타내며, 확진자 수, 사망자 수, 회복자 수 및 활동 중인 환자 수를 포함합니다.
축하합니다! COVID-19 데이터 분석 프로젝트를 완료했습니다. 질문이나 문제가 있으면 언제든지 문의하십시오.
요약
축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.



