본문 바로가기
카테고리 없음

[Python/Pandas] 데이터 추세파악 Line 차트개발

by 엘파뉴e 2021. 7. 24.

[Python/Pandas] 데이터 추세파악 Line 차트개발

 

데이터 추세파악에 유리한 line 차트 개발하기 라인으로 추세를 한눈에 쉽게 파악할 수 있다.

 

 

 

1. 그래프 모듈 'matplotlib' 와 데이터 모듈'pandas' 를 임폴트 한다.

import matplotlib.pyplot as plt
import pandas as pd

 

 

2. matplotlib 차트에서 한글폰트 를 사용할 수 있도록 폰트를 설정해준다.

plt.rc('font', family="NanumGothic")

 

3. 차트에 쓰일 데이터를 로드 한다.

file = "./data/data_2020.csv"
data = pd.read_csv(file) #데이터 읽어와 객체에 저장하기
data_Head = data.head() #데이터 모양 확인하기
print(data_Head)

       집계일자  집계시  출발영업소코드  도착영업소코드  통행시간  요일
0  20200101    4      101      105   637   2
1  20200101    4      101      105   773   2
2  20200101    4      101      105   762   2
3  20200101    4      101      105   746   2
4  20200101    4      101      105   875   2

 

 

4. 데이터 프레임 구조를 확인한다.

data_Info = data.info() #데이터 프레임 구조보기
print(data_Info)

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 152870 entries, 0 to 152869
Data columns (total 6 columns):
집계일자       152870 non-null int64
집계시        152870 non-null int64
출발영업소코드    152870 non-null int64
도착영업소코드    152870 non-null int64
통행시간       152870 non-null int64
요일         152870 non-null int64
dtypes: int64(6)
memory usage: 7.0 MB
None

 

 

5. 원하는 데이터만 가공한다.

 

5-1. 집계시 데이터에서 isin 을 통해 원하는 범위 인 6시 ~22시까지의 데이터만 불러와서, sort_values()로 시간별로 정렬한다.

data_06_22 = data[data.집계시.isin(range(6,23))] #집계시 6시부터 ~ 22시까지 만 불러오기
print(data_06_22.sort_values(by='집계시')) #시간별로 정렬해서 출력한다.

            집계일자  집계시  출발영업소코드  도착영업소코드   통행시간  요일
82028   20200715    6      101      140  16775   2
125225  20201026    6      101      110   5101   0
66049   20200609    6      101      105    713   1
66048   20200609    6      101      105    816   1
76951   20200704    6      101      135  10050   5
66047   20200609    6      101      105    894   1
141023  20201203    6      101      110   3452   3
66046   20200609    6      101      105    826   1
76952   20200704    6      101      135  12397   5
66045   20200609    6      101      105    832   1
66044   20200609    6      101      105    657   1
125235  20201016    6      101      120   6121   4
125249  20201016    6      101      115   5465   4
42786   20200414    6      101      110   2774   1
42787   20200414    6      101      110   3214   1
42788   20200414    6      101      110   3029   1
42789   20200414    6      101      110   3402   1
95557   20200818    6      101      120   8515   1
118321  20201009    6      101      110   3231   4
42798   20200412    6      101      110   3245   6
66003   20200607    6      101      140  17323   6
42800   20200414    6      101      115   4739   1
132441  20201114    6      101      130   9165   5
42801   20200414    6      101      115   5841   1
118330  20201001    6      101      115   4683   3
140981  20201202    6      101      125   7399   2
28257   20200310    6      101      110   2909   1
28256   20200310    6      101      110   3544   1
28255   20200310    6      101      110   3758   1
28254   20200310    6      101      110   3192   1
...          ...  ...      ...      ...    ...  ..
38817   20200404   22      101      125   8610   5
12583   20200131   22      101      120   6872   4
74023   20200627   22      101      135  16289   5
74032   20200627   22      101      140  16666   5
22476   20200224   22      101      140  14877   0
107492  20200915   22      101      115   5738   1
107491  20200915   22      101      115   6099   1
107490  20200915   22      101      115   4808   1
38788   20200404   22      101      120   7679   5
38779   20200404   22      101      115   5592   5
74067   20200626   22      101      110   3620   4
38778   20200404   22      101      115   5249   5
74178   20200628   22      101      105    816   6
38777   20200404   22      101      115   4666   5
38776   20200404   22      101      115   5434   5
5149    20200113   22      101      125   9153   0
12567   20200131   22      101      115   5756   4
107406  20200915   22      101      110   4041   1
107405  20200915   22      101      110   3112   1
12566   20200131   22      101      115   5805   4
12565   20200131   22      101      115   5851   4
12564   20200131   22      101      115   4886   4
22536   20200214   22      101      115   6305   4
107367  20200913   22      101      110   3548   6
5180    20200113   22      101      135  14165   0
74174   20200628   22      101      105    765   6
74175   20200628   22      101      105    870   6
74176   20200628   22      101      105    849   6
107489  20200915   22      101      115   6371   1
7741    20200120   22      101      105    873   0

[115244 rows x 6 columns]

 

 

 

5-2. value_counts()로 시간별로 카운트 한다. 

data_06_22_counting = data_06_22['집계시'].value_counts() #시간별로 카운트하기
print(data_06_22_counting)

 

13    7092
14    7091
12    7089
15    7078
11    7059
10    7038
16    7011
9     7008
17    6919
8     6849
18    6742
19    6627
7     6614
20    6518
21    6284
22    6130
6     6095
Name: 집계시, dtype: int64

 

 

 

5-3. sort_index()로 시간순으로 정렬한다.

data_06_22_counting_sorted = data_06_22_counting.sort_index() #시간별로 정렬하기 .sort_index()
print(data_06_22_counting_sorted)

 

6     6095
7     6614
8     6849
9     7008
10    7038
11    7059
12    7089
13    7092
14    7091
15    7078
16    7011
17    6919
18    6742
19    6627
20    6518
21    6284
22    6130
Name: 집계시, dtype: int64

 

 

 

6. 차트로 표현하기

집계시 별 통행회수를 카운트 해서 차트로 구현

plt.plot(data_06_22_counting_sorted.index, data_06_22_counting_sorted.values)
plt.show()

 

 

       집계일자  집계시  출발영업소코드  도착영업소코드  통행시간  요일
0  20200101    4      101      105   637   2
1  20200101    4      101      105   773   2
2  20200101    4      101      105   762   2
3  20200101    4      101      105   746   2
4  20200101    4      101      105   875   2
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 152870 entries, 0 to 152869
Data columns (total 6 columns):
집계일자       152870 non-null int64
집계시        152870 non-null int64
출발영업소코드    152870 non-null int64
도착영업소코드    152870 non-null int64
통행시간       152870 non-null int64
요일         152870 non-null int64
dtypes: int64(6)
memory usage: 7.0 MB
None
            집계일자  집계시  출발영업소코드  도착영업소코드   통행시간  요일
82028   20200715    6      101      140  16775   2
125225  20201026    6      101      110   5101   0
66049   20200609    6      101      105    713   1
66048   20200609    6      101      105    816   1
76951   20200704    6      101      135  10050   5
66047   20200609    6      101      105    894   1
141023  20201203    6      101      110   3452   3
66046   20200609    6      101      105    826   1
76952   20200704    6      101      135  12397   5
66045   20200609    6      101      105    832   1
66044   20200609    6      101      105    657   1
125235  20201016    6      101      120   6121   4
125249  20201016    6      101      115   5465   4
42786   20200414    6      101      110   2774   1
42787   20200414    6      101      110   3214   1
42788   20200414    6      101      110   3029   1
42789   20200414    6      101      110   3402   1
95557   20200818    6      101      120   8515   1
118321  20201009    6      101      110   3231   4
42798   20200412    6      101      110   3245   6
66003   20200607    6      101      140  17323   6
42800   20200414    6      101      115   4739   1
132441  20201114    6      101      130   9165   5
42801   20200414    6      101      115   5841   1
118330  20201001    6      101      115   4683   3
140981  20201202    6      101      125   7399   2
28257   20200310    6      101      110   2909   1
28256   20200310    6      101      110   3544   1
28255   20200310    6      101      110   3758   1
28254   20200310    6      101      110   3192   1
...          ...  ...      ...      ...    ...  ..
38817   20200404   22      101      125   8610   5
12583   20200131   22      101      120   6872   4
74023   20200627   22      101      135  16289   5
74032   20200627   22      101      140  16666   5
22476   20200224   22      101      140  14877   0
107492  20200915   22      101      115   5738   1
107491  20200915   22      101      115   6099   1
107490  20200915   22      101      115   4808   1
38788   20200404   22      101      120   7679   5
38779   20200404   22      101      115   5592   5
74067   20200626   22      101      110   3620   4
38778   20200404   22      101      115   5249   5
74178   20200628   22      101      105    816   6
38777   20200404   22      101      115   4666   5
38776   20200404   22      101      115   5434   5
5149    20200113   22      101      125   9153   0
12567   20200131   22      101      115   5756   4
107406  20200915   22      101      110   4041   1
107405  20200915   22      101      110   3112   1
12566   20200131   22      101      115   5805   4
12565   20200131   22      101      115   5851   4
12564   20200131   22      101      115   4886   4
22536   20200214   22      101      115   6305   4
107367  20200913   22      101      110   3548   6
5180    20200113   22      101      135  14165   0
74174   20200628   22      101      105    765   6
74175   20200628   22      101      105    870   6
74176   20200628   22      101      105    849   6
107489  20200915   22      101      115   6371   1
7741    20200120   22      101      105    873   0

[115244 rows x 6 columns]
13    7092
14    7091
12    7089
15    7078
11    7059
10    7038
16    7011
9     7008
17    6919
8     6849
18    6742
19    6627
7     6614
20    6518
21    6284
22    6130
6     6095
Name: 집계시, dtype: int64
6     6095
7     6614
8     6849
9     7008
10    7038
11    7059
12    7089
13    7092
14    7091
15    7078
16    7011
17    6919
18    6742
19    6627
20    6518
21    6284
22    6130
Name: 집계시, dtype: int64

 

 

7. 전체코드

import matplotlib.pyplot as plt
import pandas as pd

#한글폰트 사용하기, 중요! 한글폰트가 사용된  plt.show() 함수보다 앞에 위치 시켜야 함
plt.rc('font', family="NanumGothic")

file = "./data/data_2020.csv"
data = pd.read_csv(file) #데이터 읽어와 객체에 저장하기
data_Head = data.head() #데이터 모양 확인하기
print(data_Head)

data_Info = data.info() #데이터 프레임 구조보기
print(data_Info)

data_06_22 = data[data.집계시.isin(range(6,23))] #집계시 6시부터 ~ 22시까지 만 불러오기
print(data_06_22.sort_values(by='집계시')) #시간별로 정렬해서 출력한다.

data_06_22_counting = data_06_22['집계시'].value_counts() #시간별로 카운트하기
print(data_06_22_counting)

data_06_22_counting_sorted = data_06_22_counting.sort_index() #시간별로 정렬하기 .sort_index()
print(data_06_22_counting_sorted)


plt.plot(data_06_22_counting_sorted.index, data_06_22_counting_sorted.values)
plt.show()

 

 

 

8. Line 차트 설정 으로 더 보기 좋고 명확하게 구현한다. 

x = data_06_22_counting_sorted.index
labels = [str(i)+'시' for i in x] #.index로 인덱스를 가져와 변수 labels에 담는다
print(labels)

values = data_06_22_counting_sorted.values #.values 로 벨류값을 가져와 변수 values에 담는다. 
print(values)

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='s', color='r') # x 축, y축, 마커(점)설정, 색상설정
plt.title("집계시 기준 통행회수", fontsize=18) #타이틀 설정,폰트사이즈설정
plt.xlabel('집계시', fontdict= {'size':16})
plt.ylabel('통행회수', fontdict= {'size':16})
plt.show()

['6시', '7시', '8시', '9시', '10시', '11시', '12시', '13시', '14시', '15시', '16시', '17시', '18시', '19시', '20시', '21시', '22시']
[6095 6614 6849 7008 7038 7059 7089 7092 7091 7078 7011 6919 6742 6627
 6518 6284 6130]

 

 

 

9.  다른 기준으로 차트를 구현해본다. ( 기존 '집계시' 기준을 '도착영업소'기준으로 바꿔서 구현)

도착영업소기준 통행회수를 카운트 해서 차트로 구현 

data_destination_counting = data['도착영업소코드'].value_counts()
print(data_destination_counting)

data_destination_counting_sorted = data_destination_counting.sort_index()
print(data_destination_counting_sorted)

x = data_destination_counting_sorted.index
labels = [str(i) for i in x]
print(labels)

labels = ['기흥', '목천', '대전', '황간', '남구미', '동김천', '경주', '부산']
values = data_destination_counting_sorted.values

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='*', color='b')
plt.title("도착영업소 기준 통행회수", fontsize=18)
plt.xlabel('도착영업소코드', fontdict= {'size':16})
plt.ylabel('통행회수', fontdict= {'size':16})
plt.show()

105    49738
110    38526
115    26354
140     8954
130     7793
135     7428
125     7339
120     6738
Name: 도착영업소코드, dtype: int64
105    49738
110    38526
115    26354
120     6738
125     7339
130     7793
135     7428
140     8954
Name: 도착영업소코드, dtype: int64
['105', '110', '115', '120', '125', '130', '135', '140']

 

 

 

 

10. 또다른 기준으로 차트를 구현해본다 ( '요일' 기준 )

요일별 평균통행시간을 구해서 차트에 구현

data_weekdays = data.groupby(by=['요일']).mean() #평균값 .mean
print(data_weekdays)

data_weekdays_time = data_weekdays['통행시간']
print(data_weekdays_time)

x = data_weekdays_time.index
print(x)

labels = ['월', '화', '수', '목', '금', '토', '일']
values = data_weekdays_time.values

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='d', color='g')
plt.title("요일 기준 통행시간", fontsize=18)
plt.xlabel('요일', fontdict= {'size':16})
plt.ylabel('통행시간', fontdict= {'size':16})
plt.show()

            집계일자        집계시  출발영업소코드     도착영업소코드         통행시간
요일
0   2.020067e+07  11.683470    101.0  114.514421  4996.570234
1   2.020068e+07  11.737415    101.0  113.989833  4910.737777
2   2.020067e+07  11.827274    101.0  113.987466  4935.059694
3   2.020067e+07  11.848829    101.0  114.064699  5010.163163
4   2.020066e+07  11.899089    101.0  114.412568  5266.038707
5   2.020067e+07  11.308268    101.0  114.824635  5433.593481
6   2.020067e+07  12.334229    101.0  115.022740  4996.278929
요일
0    4996.570234
1    4910.737777
2    4935.059694
3    5010.163163
4    5266.038707
5    5433.593481
6    4996.278929
Name: 통행시간, dtype: float64
Int64Index([0, 1, 2, 3, 4, 5, 6], dtype='int64', name='요일')

 

 

11. 전체코드

import matplotlib.pyplot as plt
import pandas as pd

#한글폰트 사용하기, 중요! 한글폰트가 사용된  plt.show() 함수보다 앞에 위치 시켜야 함
plt.rc('font', family="NanumGothic")

file = "./data/data_2020.csv"
data = pd.read_csv(file) #데이터 읽어와 객체에 저장하기
data_Head = data.head() #데이터 모양 확인하기
print(data_Head)

data_Info = data.info() #데이터 프레임 구조보기
print(data_Info)

data_06_22 = data[data.집계시.isin(range(6,23))] #집계시 6시부터 ~ 22시까지 만 불러오기
print(data_06_22.sort_values(by='집계시')) #시간별로 정렬해서 출력한다.

data_06_22_counting = data_06_22['집계시'].value_counts() #시간별로 카운트하기
print(data_06_22_counting)

data_06_22_counting_sorted = data_06_22_counting.sort_index() #시간별로 정렬하기 .sort_index()
print(data_06_22_counting_sorted)


plt.plot(data_06_22_counting_sorted.index, data_06_22_counting_sorted.values)
plt.show()

x = data_06_22_counting_sorted.index
labels = [str(i)+'시' for i in x]
print(labels)

values = data_06_22_counting_sorted.values
print(values)

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='s', color='r')
plt.title("집계시 기준 통행회수", fontsize=18)
plt.xlabel('집계시', fontdict= {'size':16})
plt.ylabel('통행회수', fontdict= {'size':16})
plt.show()

data_destination_counting = data['도착영업소코드'].value_counts()
print(data_destination_counting)

data_destination_counting_sorted = data_destination_counting.sort_index()
print(data_destination_counting_sorted)

x = data_destination_counting_sorted.index
labels = [str(i) for i in x]
print(labels)

labels = ['기흥', '목천', '대전', '황간', '남구미', '동김천', '경주', '부산']
values = data_destination_counting_sorted.values

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='*', color='b')
plt.title("도착영업소 기준 통행회수", fontsize=18)
plt.xlabel('도착영업소코드', fontdict= {'size':16})
plt.ylabel('통행회수', fontdict= {'size':16})
plt.show()

data_weekdays = data.groupby(by=['요일']).mean() #평균값 .mean
print(data_weekdays)

data_weekdays_time = data_weekdays['통행시간']
print(data_weekdays_time)

x = data_weekdays_time.index
print(x)

labels = ['월', '화', '수', '목', '금', '토', '일']
values = data_weekdays_time.values

plt.figure(figsize=(20,10))
plt.plot(labels, values, marker='d', color='g')
plt.title("요일 기준 통행시간", fontsize=18)
plt.xlabel('요일', fontdict= {'size':16})
plt.ylabel('통행시간', fontdict= {'size':16})
plt.show()

 

댓글