본문 바로가기
IT & 데이터 사이언스/Python

[Python Data Analytics] Pandas를 활용한 데이터 입출력

by 바른 호랑이 2023. 6. 18.
728x90
반응형

안녕하세요. 바른호랑이입니다. 

이번 게시글에서는 Python의 데이터 분석을 위해 사용되는 Open source Library인 Pandas를 활용한 데이터 입출력방법에 대해 알아볼 예정입니다.

이전까지 Pandas의 대표적인 자료구조의 방법과 기초적인 조작방법에 대해 알아보았다면 이번에는 실제적인 분석을 위해 데이터를 불러오고 저장하는지에 대해 알아볼 예정입니다. Colab환경을 기준으로 작성을 해서 로컬상에서 적용할 때와는 약간의 차이가 발생할 수 있으니 해당사항은 참고하시면 되겠습니다. 추가적으로 Pandas에 대해서 다양한 정보를 확인하고 싶으시다면 아래의 사이트로 들어가서 원하는 내용을 찾아보면 좋을 것 같습니다.

※ Pandas 참고 사이트

 

pandas - Python Data Analysis Library

pandas pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language. Install pandas now!

pandas.pydata.org

※ 실습파일

Python_DataAnalysis_03(input_output).ipynb
0.10MB

# 필요 패키지 설치
!pip install pandas
!pip install numpy

'''
Google Colab에 데이터를 불러오기 위해서는 2가지 방법이 있음.
1. 수동으로 Colab에 로컬 상의 파일을 업로드하여 사용
2. file_upload 패키지를 통한 로컬상의 데이터 업로드 후 사용
3. Google Drive Mount를 통한 Cloud의 데이터 사용
'''

# file_upload를 통한 로컬 데이터 사용을 위한 패키지 로드
'''
from google.colab import files
file_upload_test = files.upload()
'''

# Google Drive의 데이터를 불러오기 위한 패키지 로드 후 drive 연결 / 사용을 위해서는 접속 허용 동의여부 체크 필요
from google.colab import drive
drive.mount('/content/drive')

# 필요 패키지 로드
import pandas as pd

'''
Pandas에서 처리가능한 대표적인 file format들
1. CSV
2. JSON
3. HTML
4. Local clipboard
5. MS Excel
6. HDF5 Format
7. SQL
'''

# CSV 파일 불러오기 // 기본 구조 : pandas.read_csv('파일경로') & 한국어로 된 파일경로 사용을 위해서는 encoding 옵션값 수정이 필요
# 로컬에서 Colab 리소스로 직접 업로드한 데이터를 사용시 데이터 로드방법
# tt_01 = pd.read_csv('/content/서울시 지하철호선별 역별 승하차 인원 정보.csv', encoding='CP949')

# Google Drive Mount를 통해 Drive내 데이터 사용시 데이터 로드방법
tt_02 = pd.read_csv('/content/drive/MyDrive/Sample data/서울 지하철호선별 역별 승하차 인원정보/서울시 지하철호선별 역별 승하차 인원 정보.csv', encoding='CP949')

'''
print(
      f'--------------------------------------------------------------------------------\
      \n{tt_01.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{tt_02.head()}\
      \n--------------------------------------------------------------------------------'
     )
'''

tt_02.head()

'''
* CSV 파일 로드 방법 및 옵션들 : pandas.read_csv('파일경로')
- path : 파일의 위치
- header : 열 이름이 되는 행 지정 / Default값은 0
- index_col : 행 인덱스가 되는 열 지정
- names : 열 이름으로 사용할 문자열 리스트
- skiprows : 첫 행기준으로 몇 개의 행을 스킵하고 불러올지 설정
            스킵하려는 행을 번호로 지정가능 ex : [1, 3, 5]
- parse_datas : 날짜 텍스트를 datetime64로 변경하여 불러올 것이지 결정(Default는 False)
- skip_footer : 마지막 몇줄을 스킵할 것인지 결정
- encoding : 텍스트 인코딩 종류를 지정
'''
file_path1 = '/content/drive/MyDrive/Sample data/서울 지하철호선별 역별 승하차 인원정보/서울시 지하철호선별 역별 승하차 인원 정보.csv'
df_csv_01 = pd.read_csv(file_path1, encoding='CP949')
df_csv_02 = pd.read_csv(file_path1, encoding='CP949', header=1)
df_csv_03 = pd.read_csv(file_path1, encoding='CP949', header=None)
df_csv_04 = pd.read_csv(file_path1, encoding='CP949', index_col=False)
df_csv_05 = pd.read_csv(file_path1, encoding='CP949', index_col='사용일자')

print(
      f'--------------------------------------------------------------------------------\
      \n{df_csv_01.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_csv_02.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_csv_03.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_csv_04.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_csv_05.head()}\
      \n--------------------------------------------------------------------------------'
     )
     
 # 데이터프레임을 CSV파일로 저장하는 방법 : DataFrame 객체.to_csv('파일경로')
'''
file_path1 = '/content/drive/MyDrive/Sample data/df_csv.csv'
df_csv_01.to_csv(file_path1)
'''

# Excel 파일은 CSV파일 로드방식과 옵션이 거의 비슷
file_path2 = '/content/drive/MyDrive/Sample data/서울 지하철호선별 역별 승하차 인원정보/서울시 지하철호선별 역별 승하차 인원 정보.xlsx'
df_excel_01 = pd.read_excel(file_path2)
df_excel_02 = pd.read_excel(file_path2, header=1)
df_excel_03 = pd.read_excel(file_path2, header=None)
df_excel_04 = pd.read_excel(file_path2, index_col=False)
df_excel_05 = pd.read_excel(file_path2, index_col='사용일자')

print(
      f'--------------------------------------------------------------------------------\
      \n{df_excel_01.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_excel_02.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_excel_03.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_excel_04.head()}\
      \n--------------------------------------------------------------------------------\
      \n\n{df_excel_05.head()}\
      \n--------------------------------------------------------------------------------'
     )
     
 # 데이터프레임을 excel파일로 저장하는 방법 : DataFrame 객체.to_excel('파일경로')
'''
file_path2 = '/content/drive/MyDrive/Sample data/df_excel.xlsx'
df_excel_01.to_excel(file_path2)
'''

'''
* JSON 파일의 일반적인 로드 방식 : pandas.read_json('파일경로')
- Mixing dicts with non-Series may lead to ambiguous ordering.에러시 해결방법
ㆍ오류원인 : 2개 이상의 딕셔너리 구조를 가지고 있을 때 발생 / 예시파일에서는
Description과 DATA로 이루어져 있음. DESCRIPTION은 사용을 안하므로 제외하고
DATA만 로드해야함.
ㆍ해결방법

from pandas.io.json import json_normalize
import json

with open('json_file.json') as f:
    file= json.load(f)

df = json_normalize(file, 'data'))

'''
from pandas.io.json import json_normalize
import json

file_path3 = '/content/drive/MyDrive/Sample data/서울 지하철호선별 역별 승하차 인원정보/서울시 지하철호선별 역별 승하차 인원 정보.json'

# json 파일 내용확인
# json.load(open(file_path3))

with open(file_path3) as f:
    file= json.load(f)

df = json_normalize(file, 'DATA')
print(df.head())

# 데이터프레임을 json파일로 저장하는 방법 : DataFrame 객체.to_json('파일경로')
'''
file_path3 = '/content/drive/MyDrive/Sample data/df_json.json'
df.head().to_json(file_path3)
'''

'''
* HTML 웹 페이지에서 데이터 로드 : pandas.read_html('웹 주소' 또는 'HTML 파일경로')
- read_html함수는 웹 페이지에 있는 <table> 태그에서 표 형식의 데이터를 모두 찾아서 데이터 프레임으로 변환함.
- 웹에 있는 다양한 tag들 및 원하는 데이터를 조정하여 추출하는게 어려우므로 웹 크롤링에 대한 추가적인 작업을
한 이후에 데이터를 가져오는 것이 좋음.
'''
url = 'https://finance.naver.com/world/'
pd.read_html(url, encoding='CP949')

# 웹 스크래핑을 위한 추가 패키지 로드
from bs4 import BeautifulSoup as bf
import requests as rq
import re

# 패키지를 활용하여 해당 웹 페이지의 HTML 소스 긁어오기
resp = rq.get(url)
# lxml은 해당 페이지의 HTML 소스의 string을 분석하기위한 Beautifulsoup의 모듈
soup = bf(resp.text, 'lxml')

print(soup)

P.S 더 나은 개발자가 되기위해 공부중입니다. 잘못된 부분을 댓글로 남겨주시면 학습하는데 큰 도움이 될 거 같습니다.

728x90
반응형

댓글