python basic(2021-07-18)

Hyunjeong Lee·2021년 7월 18일
0

데이터분석의 4단계

1.데이터 불러오기
2.데이터 살펴보기
3.데이터 가공하기
4.데이터 시각화

[상권데이터분석]

1.데이터 불러오기
라이브러리 불러오기
import pandas as pd
데이터 불러오기
commercial = pd.read_csv('./data/commercial.csv')
commercial

2.데이터 살펴보기
2-1.list(commercial)
2-2.commercial.groupby('상가업소번호')['상권업종소분류명'].count().sort_values(ascending=False)
2-3.category_range = set(commercial['상권업종소분류명'])
print(category_range, len(category_range))
2-4.메모장에 옮겨서 '치킨' 키워드로 검색 : 간단한 일은 간단한 방법으로!

3.데이터 가공하기
분석하고 싶은것은 서울에 있는 치킨집
3-1. 도로명 주소를 시,구, 나머지로 잘라줍니다
commercial[['시', '구', '상세주소']] = commercial['도로명주소'].str.split(' ', n=2, expand=True)
commercial.tail(5)
3-2. 서울시만 픽업
seoul_data = commercial[commercial['시'] =='서울특별시']
seoul_data
3-3. 데이터 검증
city_type = set(seoul_data['시'])
city_type, len(city_type)
3-4. 서울에 있는 치킨집만 픽업
seoul_chicken_data = seoul_data[ seoul_data['상권업종소분류명'] == '후라이드/양념치킨']
seoul_chicken_data
3-5. 데이터 검증
set(seoul_chicken_data['상권업종소분류명'])
3-6. 구별 치킨집 수
groupdata = seoul_chicken_data.groupby('구')
group_by_category = groupdata['상권업종소분류명']
chicken_count_gu = group_by_category.count()
sorted_chicken_count_gu = chicken_count_gu.sort_values(ascending=False)
sorted_chicken_count_gu

4.데이터 시각화
4-1. 맷플롯라이브러리 가져오기&한글 글자체 설정
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = "AppleGothic"
4-2. 바 그래프 그리기
plt.figure(figsize=(10,5))
plt.bar(sorted_chicken_count_gu.index, sorted_chicken_count_gu)
plt.title('구에 따른 치킨가게 수의 합계')
plt.xticks(rotation =90)
plt.show()
4-3. 지도에 나타내기
*사전 준비
folium설치
conda install -c conda-forge folium
가져오기
import folium
import json
4-3-1. 지도데이터 가져오기
seoul_state_geo = './data/seoul_geo.json'
geo_data = json.load(open(seoul_state_geo, encoding='utf-8'))
4-3-2. 지도에 나타내기
map = folium.Map(location=[37.5502, 126.982], zoom_start=10)

folium.Choropleth(geo_data=geo_data,
data=chicken_count_gu,
columns=[chicken_count_gu.index, chicken_count_gu],
fill_color='PuRd',
key_on='feature.properties.name').add_to(map)

map

지도데이터 가져오기
뽑은 데이터 가져오기
컬럼 설정(바 그래프 그릴때와 같음. 인덱스와 그 값)
색칠하기
색칠영역 설정(프로퍼티중 어떤 항목을 픽업할것인가)

[유동인구 데이터분석]

1.데이터 불러오기
import pandas as pd
population = pd.read_csv('./data/population07.csv')

2.데이터 살펴보기
2-1.population['연령대(10세단위)'], len(set(population['연령대(10세단위)']))
2-2.set(population['시'])
2-3.set(population['군구']),len(set(population['군구']))

3.데이터 가공하기
sum_of_population_by_gu = population.groupby('군구')['유동인구수'].sum()

구별 유동 인구수(한번에 구하기)

4.데이터 시각화
4-1.맷플롯라이브러리 불러오기& 한글 글자체 설정
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = "AppleGothic"
4-2.막대 그래프 그리기
plt.figure(figsize=(10,5))
plt.bar(sorted_sum_of_population_by_gu.index, sorted_sum_of_population_by_gu)
plt.title('2020년 7월 서울 군구별 유동인구 수')
plt.xlabel('군구')
plt.ylabel('유동인구수(명)')
plt.xticks(rotation= -45)
plt.show()

강남 일일 유동인구만 떼서 보기
plt.figure(figsize=(10,5))

date = []
for day in population_gangnam_daliy.index:
date.append(str(day))

plt.plot(date, population_gangnam_daliy)
plt.title('2020년 7월 서울 강남구 날짜별 유동인구 수')
plt.xlabel('날짜')
plt.ylabel('유동인구수(천만명)')
plt.xticks(rotation=-90)
plt.show()

4-3.가공한 데이터 지도에 나타내기
seoul_state_geo = './data/seoul_geo.json'
geo_data = json.load(open(seoul_state_geo, encoding= 'utf-8'))
folium.Choropleth(geo_data=geo_data,
data = sum_of_population_by_gu,
colums=[sum_of_population_by_gu.index, sum_of_population_by_gu],
fill_color= 'PuRd',
key_on ='properties.name').add_to(map)
map

[상권과 유동인구 합쳐서 분석하기]

1.데이터 리셋하고 합치기
new_chicken_count_gu = pd.DataFrame(chicken_count_gu).reset_index()
new_chicken_count_gu

new_sum_of_population_by_gu = pd.DataFrame(sum_of_population_by_gu).reset_index()
new_sum_of_population_by_gu

join on
new_sum_of_population_by_gu = pd.DataFrame(sum_of_population_by_gu).reset_index()
new_sum_of_population_by_gu

2.치킨집당 유동인구수 구하기
gu_chicken['유동인구수/치킨집수'] = gu_chicken['유동인구수']/gu_chicken['상권업종소분류명']
gu_chicken = gu_chicken.sort_values(by='유동인구수/치킨집수')
gu_chicken

3.그래프로 확인하기
plt.figure(figsize=(10,5))
plt.bar(gu_chicken['구'], gu_chicken['유동인구수/치킨집수'])
plt.xlabel('구')
plt.ylabel('유동인구수/치킨집수')
plt.xticks(rotation=90)
plt.show()

0개의 댓글