프로젝트 목차
- 데이터 읽기: 자동차 리콜 데이터를 불러오고 Dataframe 구조를 확인
1.1. 데이터 불러오기 - 데이터 정제: 결측치 확인 및 기초적인 데이터 변형
2.1. 결측치 확인
2.2. 중복값 확인
2.3. 기초적인 데이터 변형 - 데이터 시각화: 각 변수 별로 추가적인 정제 또는 feature engineering 과정을 거치고 시각화를 통하여 데이터의 특성 파악
3.1. 제조사별 리콜 현황 출력
3.2. 모델별 리콜 현황 출력
3.3. 월별 리콜 현황 출력
3.4. 생산연도별 리콜 현황 출력
3.5. 4분기 제조사별 리콜 현황 출력
3.6. 하반기 생산연도별 리콜 현황 출력
3.7. 워드 클라우드를 이용한 리콜 사유 시각화
3. 데이터 시각화
각 column의 변수별로 어떠한 데이터 분포를 하고 있는지 시각화를 통하여 알아봅시다.
3.1. 제조사별 리콜 현황 출력
df.groupby("manufacturer").count()["model"].sort_values(ascending=False)
#pd.dataframe을 통해서 깔끔하게 보여줌
pd.DataFrame(df.groupby("manufacturer").count()["model"].sort_values(ascending=False)).rename(columns={"model": "count"})
* manufacturer 과 count 컬럼의 높이 차이가 나는 이유는
manufacturer은 인덱스의 역할을 하고있기 때문!
시각화하는 방법
ptl.figure(figsize = (20,10))
sns.set(font, rc, stytle)
ax = sns.countplot(x = ,data = , palette, order )
plt.figure(figsize=(20,10))
# 한글 출력을 위해서 폰트 옵션을 설정합니다.
sns.set(font="NanumBarunGothic",
rc={"axes.unicode_minus":False},
style='darkgrid')
ax = sns.countplot(x="manufacturer", data=df, palette="Set2", order=tmp.index)
#order 설정을 통해서 내림차순으로!!!
plt.xticks(rotation=270) #270도 만큼 돌아감 , 안돌리면 글자가 겹쳐짐!
plt.show()
3.2. 모델별 리콜 현황 출력
차량 모델별 리콜 건수 분포를 막대 그래프로 확인해보겠습니다.
#함수를 뒤에 이어서 붙여 써줌!
#내림차순으로 컬럼명칭 바꿔서 상위 10개만 출력
pd.DataFrame(df.groupby("model").count()["start_year"].sort_values(ascending=False)).rename(columns={"start_year": "count"}).head(10)
모델은 굉장히 많으므로, 상위 50개 모델만 뽑아서 시각화를 진행해보겠습니다.
#iloc 은 인덱스로 슬라이싱 하는 함수
tmp = pd.DataFrame(df.groupby("model").count()["manufacturer"].sort_values(ascending=False))
tmp = tmp.rename(columns={"manufacturer": "count"}).iloc[:50]
#시각화 해보기
# 그래프의 사이즈를 조절합니다.
plt.figure(figsize=(10,5))
# seaborn의 countplot 함수를 사용하여 출력합니다.
sns.set(font="NanumBarunGothic",
rc={"axes.unicode_minus":False},
style='darkgrid')
ax = sns.countplot(x="model", data=df[df.model.isin(tmp.index)], palette="Set2", order=tmp.index)
plt.xticks(rotation=270)
plt.show()
3.3 월별 리콜 현황 출력
#막대 그래프로 확인
pd.DataFrame(df.groupby("recall_month").count()["start_year"].sort_values(ascending=False)).rename(columns={"start_year": "count"})
#인덱스 값을 컬럼으로 바꾸는 방법!
#tmp_reset_index()
tmp = pd.DataFrame(df.groupby("recall_month").count()["start_year"].sort_values(ascending=False)).rename(columns={"start_year": "count"})
tmp.reset_index()
tmp = tmp.reset_index()
tmp['recall_month']
# 그래프의 사이즈를 조절합니다.
plt.figure(figsize=(10,5))
# seaborn의 countplot 함수를 사용하여 출력합니다.
sns.set(style="darkgrid")
ax = sns.countplot(x="recall_month", data=df, palette="Set2")
plt.show()
<실행결과>
3.4. 생산연도별 리콜 현황 출력
#reset_index 까지 진행 후 그래프!
tmp = pd.DataFrame(df.groupby("start_year").count()["model"]).rename(columns={"model": "count"}).reset_index()
# 그래프의 사이즈를 조절합니다.
plt.figure(figsize=(10,5))
# seaborn의 lineplot 사용
sns.set(style="darkgrid")
sns.lineplot(data=tmp, x="start_year", y="count")
plt.show()
퀴즈 1. 2020년에 리콜 개시가 가장 많이 일어난 달(month)과 가장 적게 일어난 달의 차이(건수)를 구하세요.
<1. 직접 짜본 코드..>
#reset_index 하니까 rename 설정한거랑 orderby 설정한게 다 날라가는데?
#잘못 짠듯
MAX = pd.DataFrame(df[df['recall_year'] == 2020].groupby("start_year").count()["manufacturer"].sort_values(ascending = False)).rename(columns={"manufaturer" : "count"}).reset_index().head(1)
MAX.iloc[0]["manufacturer"]
MIN = pd.DataFrame(df[df['recall_year'] == 2020].groupby("start_year").count()["manufacturer"].sort_values(ascending = False)).rename(columns={"manufaturer" : "count"}).reset_index().tail(1)
MIN.iloc[0]["manufacturer"]
# 퀴즈의 답을 구하여 quiz_1 변수에 저장합니다.
# integer 형 상수값으로 저장합니다.
quiz_1 = MAX.iloc[0]["manufacturer"] - MIN.iloc[0]["manufacturer"]
quiz_1
# 실행결과 group by를 recall_year이 아니라 recall_month로 해줘야되는것을 알게 되었다....
#아침이라..? 머리가 안돌아가네
<2. 직접 짜본 코드..>
tmp = pd.DataFrame(df.groupby("recall_month").count()["manufacturer"].sort_values(ascending = False)).rename(columns={"manufacturer":"count"})
#iloc 함수를 사용해서 정렬한 값중 제일 큰 데이터는 0, 제일 마지막 데이터는 인덱스 -1에 있음tmp.iloc[0]["count"] - tmp.iloc[-1]["count"]
3.5. 4분기 제조사별 리콜 현황 출력
가장 최근 데이터인 2020년 4분기(10, 11, 12월) 제조사별 리콜 현황을 시각화해봅시다.
#조건에 맞는 데이터를 추출하는 방법!!!
# 논리연산을 이용한 조건을 다음과 같이 사용하면 해당 조건에 맞는 데이터를 출력할 수 있습니다.
# recall_month가 10,11,12 인 데이터만 가져와라
df[df.recall_month.isin([10,11,12])].head()
# 그래프를 출력합니다.
#한글 출력을 위한 폰트 설정
plt.figure(figsize=(20,10))
sns.set(font="NanumBarunGothic",
rc={"axes.unicode_minus":False},
style='darkgrid')
ax = sns.countplot(x="manufacturer", data=df[df.recall_month.isin([10,11,12])], palette="Set2")
plt.xticks(rotation=270)
plt.show()
3.6. 하반기 생산연도별 리콜 현황 출력
이번에는 2020년 하반기(7~12월)에 개시된 리콜 건들을 생산 개시 연도를 기준으로 시각화해봅시다.
# 해당 column을 지정하여 series 형태로 출력할 수 있습니다.
df[df.recall_month>=7].head()
# 그래프를 출력합니다.
plt.figure(figsize=(10,5))
sns.set(style="darkgrid")
ax = sns.countplot(x="start_year", data=df[df.recall_month>=7], palette="Set2")
plt.show()
3.7. 워드 클라우드를 이용한 리콜 사유 시각화
#recall 사유 -> df.cause
# 글로 되어있는 형식은 워드클라우드 라이브러리를 사용 함!
# 워드 클라우드 생성을 도와주는 패키지를 가져옵니다.
try:
from wordcloud import WordCloud, STOPWORDS # stopwords 는 문법적인 성분을 배제하기 위한 집합
except:
!pip install wordcloud
from wordcloud import WordCloud, STOPWORDS
# 문법적인 성분들을 배제하기 위해 stopwords들을 따로 저장해둡니다.
#시각화할때 배제 하자! 라는 목적
set(STOPWORDS)
#한국어의 경우는 별도로 stopwords 를 저장해서 사용하거나 다른 라이브러리를 사용해야함
# 손으로 직접 리콜 사유와 관련이 적은 문법적 어구들을 배제해보겠습니다.
spwords = set(["동안", "인하여", "있는", "경우", "있습니다", "가능성이", "않을", "차량의", "가", "에", "될", "이",
"인해", "수", "중", "시", "또는", "있음", "의", "및", "있으며", "발생할", "이로", "오류로", "해당"])
# 리콜 사유에 해당하는 열의 값들을 중복 제거한 뒤 모두 이어붙여서 text라는 문자열로 저장합니다.
text = ""
for c in df.cause.drop_duplicates():
text += c
text[:100]
# 한글을 사용하기 위해서는 폰트를 지정해주어야 합니다.
wc1 = WordCloud(max_font_size=200, stopwords=spwords, font_path='/usr/share/fonts/truetype/nanum/NanumGothic.ttf',
background_color='white', width=800, height=800)
wc1.generate(text)
plt.figure(figsize=(10, 8))
plt.imshow(wc1)
plt.tight_layout(pad=0)
plt.axis('off')
plt.show()
#stopword를 통해서 무의미한 부분은 제거되고 중요한 키워드 역할을 하는 애들이 시각화가 되었군!!!
#신기하다
퀴즈 2. 기아자동차(주)의 제품 중 가장 최근에 리콜이 개시된 제품의 모델명을 구하세요.
tmp = df[df['manufacturer'] == '기아자동차(주)'].sort_values(by=["recall_year","recall_month","recall_day"], ascending = False).iloc[0]
tmp.model
세번째 프로젝트 끝!
'Data Analysis' 카테고리의 다른 글
[Python] 테스트빈도 분석1 - 영어단어분석 프로젝트(불용어(stopword),표제어 추출(Lemmatization) (0) | 2021.12.11 |
---|---|
[데이터분석](Project 3) 자동차 리콜 데이터 분석 1 (0) | 2021.10.02 |
[데이터분석]지하철 승하차 인원 분석 프로젝트3 (0) | 2021.10.01 |
[데이터분석](Project2) 지하철 승하차 인원 분석 프로젝트2 (0) | 2021.09.30 |
[데이터분석](Project2) 지하철 승하차 인원 분석하기 (0) | 2021.09.29 |