본문 바로가기

AI/StudyNote

Python #CSV #데이터분석(교통) #시각화

활용 데이터 #01 : 티머니(https://pay.tmoney.co.kr/index.dev)

교통카드 통계자료

subwayfee.csv

 

 

 

활용 데이터 #02 서울 열린데이터 광장 https://data.seoul.go.kr/

서울의 각 역의 시간대별 승하차 데이터

subwaytime.csv


대중교통 데이터 활용

 

1. csv 확인 (csv 헤더 내용은 본문 최상단 참고)

import csv

f = open('.\\data\\subwayfee.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)

for row in data:
    for i in range(4,8):#정수로 변환할 열 지정
        row[i] = int(row[i])
    print(row)

f.close()

 

2. 유임승차비율이 가장 높은 역은 어디일까요?

#강사님 답안
#홍대입구 2호선 0.95

import csv

f = open('.\\data\\subwayfee.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)

mx = 0
rate = []

for row in data:
    for i in range(4,8):
        row[i] = int(row[i]) #4~7열의 데이터를 정수로 형변환
    
    #호선명, 지하철역, 비율
    if row[6] != 0 and (row[4] + row[6]) > 100000: #7열의 데이터가 0인 경우와 5열+6열이 100000이상의 데이터인 경우        rate = row[4] / (row[6] + row[4])
        rate = row[4] / (row[6] + row[4]) #유임승차 비율
        if rate > mx: #유임승차비율이 mx 보다 크다면
            mx = rate #mx 업데이트
            max_station = row[3] + '' + row[1] #역정보 업데이트
            
    
print(max_station, round(mx*100, 2))
f.close()

홍대입구 2호선 95.34

 

 

3. 유무임 승차 인원이 가장 많은 역을 출력

- 실행결과
  유임 승차 : 강남 2호선 000000
  유임 하차 : 강남 2호선 000000
  무임 승차 : 종로 3가 1호선 000000
  무임 하차 : 제기동 1호선 000000

import csv

f = open('.\\data\\subwayfee.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)

mx = [0]*4 #0이 4개 들어갈 리스트 생성
mx_station = ['']*4
label = ['유임승차', '유임하차','무임승차','무임하차']

for row in data:
    for i in range(4,8): # 4부터 7까지 반복
        row[i] = int(row[i]) #형변환
        if row[i] > mx[i-4]: #만약 i열이 mx 열보다 값이 크다면
            mx[i-4] = row[i] #mx열 데이터 업데이트
            mx_station[i-4] = row[3] + ' ' + row[1] #스테이션 정보 업데이트
            
for i in range(4): #출력을 위한 반복
    print(label[i] + ' : ' + mx_station[i], mx[i])

 

4. 모든 역의 승하차 비율을 파이 차트로 나타내고 저장
- 타이틀 : 00 역 00호선
- 파일명 : 00역 00호선.png

import csv
import matplotlib.pyplot as plt

f = open('.\\data\\subwayfee.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기
next(data)

label = ['유임승차', '유임하차','무임승차','무임하차']
c = ['#14ccc0', '#389993', '#ff1c6a', '#cc14af']

plt.rc('font', family = 'Malgun Gothic') #맑은 고딕을 기본 글꼴로 설정

for row in data:
    for i in range(4,8):
        row[i] = int(row[i])
    plt.figure(dpi = 300)
    plt.title(row[3] + ' ' + row[1])
    plt.pie(row[4:8], labels = label, colors = c, autopct = '%1.f%%')
    plt.axis('equal')
    plt.savefig(row[3]+ ' ' + row[1] + '.png')#저장
    plt.show()
    
f.close()

 


시간대별 승하차 데이터 활용

 

1. 전체 역의 7시의 하차 기록 확인

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)

result = [] 

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체
    result.append(row[10])#7시의 하차 기록
    
print(len(result))#역이 개수 체크
f.close()

import matplotlib.pyplot as plt

result.sort()#오름차순 정렬
plt.bar(range(len(result)), result)
plt.show()

 

 

2. #출근시간대(7시~9시)만 담음

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)
result = [] 

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체
    result.append(sum(row[10:15:2]))#7~9시의 하차 기록(11번째부터 13, 15열을 합함)
    
print(len(result))#역이 개수 체크
f.close()

import matplotlib.pyplot as plt

result.sort()#오름차순 정렬
plt.bar(range(len(result)), result)
plt.show()

 

3. 출근(7~9시) 동안 80만 명 이상이 들어오는 역은?

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)

mx = 0
ma_station = ''

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체
    
    if sum(row[10:15:2]) > mx : 
        mx = sum(row[10:15:2])
        max_station = row[3] + '(' + row[1]+')' #역정보 업데이트

print(max_station, mx)
f.close()

신림(2호선) 809541

 

4. 출근 3시간 동안 사람들이 가장 많이 내린 역은?

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)

mx = 0
ma_station = ''

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체

    if sum(row[11:16:2]) > mx : #
        mx = sum(row[11:16:2])
        max_station = row[3] + '(' + row[1]+')' #역정보 업데이트

print(max_station, mx)
f.close()

강남(2호선) 984427

 

5. 시간을 입력해 승차인원이 가장 많은 역을 검색

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)

mx = 0
ma_station = ''

time = int(input("몇 시의 승차인원이 가장 많은 역이 궁금하세요? :"))

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체

    temp = row[4+(time - 4)*2]

    #pattern 02: 
    #temp = row[time + (time - 4)] #역의 시간을 입력값을 대입해 row기준으로 찾음

    if temp > mx : 
        mx = temp
        max_station = row[3] + '(' + row[1]+')' #역정보 업데이트

print(max_station, mx)
f.close()

몇 시의 승차인원이 가장 많은 역이 궁금하세요? :23

강남(2호선) 145504

 

6. 24시간 동안 승차 인원이 가장 많은 역을 시간대별로 출력

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

next(data)
next(data)

mx = [0]*24
mx_station = ['']*24


for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체
    for i in range(24):
        temp = row[i*2+4] #데이터를 0부터 23까지 반복으로 각 시간별 승차데이터를 담음
        #print(temp)
        if temp > mx[i]:
            mx[i] = temp
            t = (i + 4)% 24 #시간이 24가 넘으면 1,2,3으로 출력되게
            if t == 0: #시간이 0이라면 24로 표시
                t = 24
            mx_station[i] = row[3] + '('+ str(t)+')'

f.close()


import matplotlib.pyplot as plt

plt.rc('font', family = 'Malgun Gothic') #맑은 고딕을 기본 글꼴로 설정
plt.rcParams['axes.unicode_minus'] = False #그래프 - 깨지는 현상해결

plt.bar(range(24), mx)
plt.xticks(range(24), mx_station, rotation = 90)#x축데이터 정보 및 각도 조정

plt.show()

 

6. 지하철 시간대별 승하차 인원 추리를 꺾은선 그래프로 표시(예외처리 x)

- 조사할 지하철 입력

- 승차 : 빨간색, 하차 : 파란색

import csv
f = open('.\\data\\subwaytime.csv') #데이터 경로
data = csv.reader(f) #데이터 불러오기

#station = input("조사할 지하철을 입력하세요 :")
station = '강남구청'
s_line = '7호선'

next(data)
next(data)

line = ''
board = ['']*24
quit = ['']*24

for row in data:
    row[4:]=map(int, row[4:]) #맵으로 row의 4이후의 수를 정수로 모두 교체

    if station in row[3] and s_line in row[1]:
        for i in range(24):
            #temp = row[i*2+4]  
            board[ni] = row[i*2+4]
            quit[ni] = row[i*2+5]
        line = row[1]
        st_name = row[3]
       
                    
f.close()


import matplotlib.pyplot as plt

plt.rc('font', family = 'Malgun Gothic') #맑은 고딕을 기본 글꼴로 설정
plt.rcParams['axes.unicode_minus'] = False #그래프 - 깨지는 현상해결

plt.plot(board, label = '승차', color = 'b')
plt.plot(quit, label = '하차', color = 'r')
plt.legend()

plt.title(st_name+' '+s_line+ '의 시간대별 승하차 인원 추이') #제목설정하기

plt.show()

반응형