카테고리 없음

pandas의 read_excel()

물극필반99 2019. 12. 10. 14:47
반응형

R, Python 분석과 프로그래밍의 친구 (by R Friend) 님의 글을 제가 참고할 수 있도록 수정하였습니다.
출처: https://rfriend.tistory.com/464 [R, Python 분석과 프로그래밍의 친구 (by R Friend)]

 

sales_per_region.xlsx
0.01MB
pandas_excel.py
0.00MB

(1) 엑셀 자료로 부터 읽어올 데이터셋은 'Sheet1' 이름의 첫번째 쉬트에 있으며, 3행 A열 부터 ~ 10행 D열까지의 Cell에 있는 데이터입니다.  (sheet_name = 'Sheet1', header = 2)

(2) '3행은 칼럼 이름(header)'이며, 'A열의 'id' 칼럼은 index로 사용'하고자 합니다. (header = 2, index_col='id')

(3) 'region' 칼럼은 문자열(string), 'sales_representative' 칼럼은 정수형(integer), 'sales_amount' 칼럼은 부동소수형(float)의 데이터 형태(data type)입니다. (dtype = {'region': str, 'sales_representative': np.int64, 'sales_amount': float})

(4) pandas DataFrame으로 불러왔을 때 'sales_amount' 칼럼에 천 단위 구분 기호 콤마(',')는 없애고 싶습니다. (thousands = ',')

(5) 총 읽어올 행의 개수(number of rows)는 10개로 한정하고 싶습니다. (nrows=10)

(6) 11번째 행에 '# ignore this line' 처럼 '#' (comment character) 으로 시작하면 그 뒤의 행 전체는 무시하고자 합니다. (comment = '#')


from IPython.display import display
import os
import numpy as np
import pandas as pd

base_dir = 'D:/03.Study/01.SD/jemudata' # set directory with yours

excel_file = 'sales_per_region.xlsx'

excel_dir = os.path.join(base_dir, excel_file)

# read a excel file and make it as a DataFrame

df_from_excel = pd.read_excel(excel_dir, # write your directory here
sheet_name = 'Sheet1',
header = 2,
#names = ['region', 'sales_representative', 'sales_amount'],
dtype = {'region': str,

'sales_representative': np.int64,

'sales_amount': float}, # dictionary type
index_col = 'id',
na_values = 'NaN',
thousands = ',',
nrows = 10,
comment = '#')

display(df_from_excel)

     region  sales_representative  sales_amount
id                                             
1     seoul                   510        1500.0
2    inchon                   430        1260.0
3     busan                   320        1090.0
4   guangju                   180         550.0
5     ulsan                   135         380.0
6    sejong                   110         290.0
7    jeunju                    83         235.0

 

반응형