프로젝트/토이 프로젝트(개인)

[ONLY PYTHON] 자전거 대여 현황 데이터다루기 / python을 이용한 공공데이터활용

으노으뇨 2023. 12. 2. 19:16
728x90
반응형
SMALL
개요

서울시 대여소별 자전거  대여 현황 및 이동거리별 운동량에 대한 데이터를 수정하고 가공한 데이터에 대해데이터를 그룹핑하고 시각화하는 것을 응용하였다.

주로 사용된 기술 또는 스킬

  1. 파이썬 파일 처리
  2. pandas를 이용한 그룹핑
  3. 파이썬을 이용해 그래프로 데이터 시각화 하기
내용

안녕하세용~~ 

어느덧 추운겨울날이 왔네요ㅠ 저도 이제 일년간 틈틈히 혼자 공부하던 파이썬에 대해서

실제로 어떻게 사용할 수 있는지 스스로 토이프로젝트식으로 글을 작성해보고자 합니다 ㅎㅎ

우선은 파이썬을 이용해서 공공데이터를 다루는 프로그램을 만들어볼게요!

실제 데이터를 활용한 데이터 뷰어


사용된 라이브러리 및 클래스

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import pandas as pd
import datetime as dt

사용된 데이터 

우선 공공데이터중 서울시의 대여소별 자전거 대여현황 파일입니다!

제가 다룰 부분이 크지 않아서 어느정도 제가 수정을 했습니다. 

cycle.csv
0.00MB

내용은 아래와 같은데용

너무 많으면 다루기 불편하고 그래서 우선 대폭 줄였습니다.!!!


프로그램 구현

CSV파일 불러오기
plt.rcParams['font.family']='MalgunGothic'
df=pd.read_csv('cycle.csv',encoding='cp949')
print(df.dtypes)
print(df.shape)
print(df.info())
print(df.head())

소스로 파일을 불러오고 확인한다.

해당 파일의 dtypes
해당 데이터 프레임의 모양
해당 데이터프레임의 정보
해당 데이터프레임의 헤더정보

CSV파일의 Date 컬럼 데이터 변환

현재 cycle테이블의 Date 컬럼은 object형태입니다. datetime으로 변환하겠습니다.

df['date']=pd.to_datetime(df['date'])
print(df.info())

위 소스를 통해 date컬럼은 데이트타임 형으로 변환되었습니다.

datetime으로 변환된 모습

energy컬럼을 수치데이터로 변경 및 결측치 처리

energe 데이터에 결측치가 있다. 만약 에너지 사용량의 평균을 구할때 결측치때문에 오류 또는 정확하지 않은 값이 추출될 수 있어 결측치를 처리해주기 위해 판다스의 to_numeric을 이용하였다.

우선 해당 데이터를 object로 변경한 뒤 진행한다.

df['energy']=df['energy'].astype('object')
df['energy']=pd.to_numeric(df['energy'], errors='coerce').fillna(df['energy'].mean())

그럼 결측치가 모두 평균으로 처리된다.

 

전체소스

전체소스는 아래와 같습니다. 사용자의 편의성을 위해 데이터를 시각화하는 라이브러리를 사용했습니다.

import tkinter as tk
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt

root = tk.Tk()
root.title("CSV Viewer")

text_area = None
info_text = None
current_df = None

def load_csv():
    global text_area, info_text, current_df
    file_path = filedialog.askopenfilename()
    df = pd.read_csv(file_path)
    show_data(df)
    current_df = df
    enable_buttons()


def show_data(dataframe):
    global text_area
    if text_area:
        text_area.delete('1.0', tk.END)
    else:
        text_frame = tk.Frame(root)
        text_frame.pack(side=tk.LEFT)

        text_area = tk.Text(text_frame)
        text_area.pack()

    text_area.insert(tk.END, dataframe.to_string())

def show_main():
    global text_area
    if text_area:
        text_area.delete('1.0', tk.END)
        text_area.insert(tk.END, current_df.to_string())


def plot_date_graph():
    date_counts = current_df['date'].value_counts()
    date_frame = pd.DataFrame({'date': date_counts.index, 'count': date_counts.values})
    plt.bar(date_frame['date'], date_frame['count'])
    plt.xlabel('Date')
    plt.ylabel('Count')
    plt.title('Date Counts')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()


def plot_no_energy_graph():

    no_energy_means = current_df.groupby('No')['energy'].mean()
    plt.bar(no_energy_means.index.astype(str), no_energy_means.values)
    plt.xlabel('No')
    plt.ylabel('Average Energy')
    plt.title('Average Energy by No')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()


def show_no_distance_table():
    global text_area
    no_distance_sum = current_df.groupby('No')['use(distance)'].sum()
    no_distance_df = pd.DataFrame({'No': no_distance_sum.index, 'Total Distance': no_distance_sum.values})
    if text_area:
        text_area.delete('1.0', tk.END)
        text_area.insert(tk.END, no_distance_df.to_string())
    else:
        text_frame = tk.Frame(root)
        text_frame.pack(side=tk.LEFT)

        text_area = tk.Text(text_frame)
        text_area.pack()

        text_area.insert(tk.END, no_distance_df.to_string())


def enable_buttons():
    main_button['state'] = 'normal'
    date_button['state'] = 'normal'
    no_energy_button['state'] = 'normal'
    no_distance_button['state'] = 'normal'

load_button = tk.Button(root, text="Load CSV", command=load_csv)
load_button.pack()

main_button = tk.Button(root, text="Main", command=show_main, state='disabled')
main_button.pack()

date_button = tk.Button(root, text="Date Graph", command=plot_date_graph, state='disabled')
date_button.pack()

no_energy_button = tk.Button(root, text="No Energy Graph", command=plot_no_energy_graph, state='disabled')
no_energy_button.pack()

no_distance_button = tk.Button(root, text="No Distance Table", command=show_no_distance_table, state='disabled')
no_distance_button.pack()

root.mainloop()

 

728x90
반응형
LIST