04-30 00:01
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Programming / Python] Pandas 모듈을 이용하여 엑셀(Excel) 데이터 가져오기 및 Excel 파일로 데이터 저장하기 본문

Programming/Python

[Programming / Python] Pandas 모듈을 이용하여 엑셀(Excel) 데이터 가져오기 및 Excel 파일로 데이터 저장하기

cinema4dr12 2017. 11. 24. 22:45

이번 포스팅에서는 Python의 Data 데이터 분석 라이브러리(모듈)인 pandas를 이용하여 Microsoft Excel 파일의 데이터를 불러오는 방법에 대하여 알아보도록 하겠습니다.


샘플 코드는 다음과 같습니다:

1
2
3
4
5
6
7
8
9
10
import pandas as pd
 
inputExcelFile = {YOUR_EXCEL_FILE_PATH}
if os.path.isfile(inputExcelFile):
    xl = pd.ExcelFile(inputExcelFile)
else:
    print("[ERROR] Failed to load Excel File : %s" % (inputExcelFile))
 
# Load a sheet into a DataFrame by name: df
df = xl.parse(''.join(xl.sheet_names))
cs

 


반대로 Data Frame을 Excel 파일로 저장하는 방법에 대해 알아보도록 하겠습니다.

우선 Excel 파일로 저장을 위해서는 Open Python Excel(openpyxl) 모듈 설치가 필요합니다:

설치를 위해 Command Line Tool에서 pip 명령을 사용하거나:

> pip install openpyxl


Anaconda가 설치되어 있는 경우,

> conda install openpyxl

와 같이 입력하여 모듈을 설치합니다.


아래 코드는 Data Frame을 Excel 파일로 저장하는 샘플 코드입니다:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# import modules
import pandas as pd
import numpy as np
 
# index_format(index) & columns_format(columns)정의
index_format = [12345678910]
columns_format = ['x''y']
 
# DataFrame 초기화
values = pd.DataFrame(index=index_format, columns=columns_format)
 
# x & y 값 정의
= index_format
= np.sin(x)
 
for ii in range(values.shape[0]):
    # fill in x values into column index zero of values
    values.iloc[ii,0= x[ii]
    # fill in x values into column index one of values
    values.iloc[ii,1= y[ii]
 
# saves DataFrame(values) into an Excel file
values.to_excel('./test.xlsx',
                sheet_name='Sheet1',
                columns=columns_format,
                header=True,
                index=index_format,
                index_label="y = sin(x)",
                startrow=1,
                startcol=0,
                engine=None,
                merge_cells=True,
                encoding=None,
                inf_rep='inf',
                verbose=True,
                freeze_panes=None)
cs


Line 10에서 Data Frame values를 초기화하였는데 초기화 했을 때에는 다음과 같은 형태가 됩니다:

> values 
      x    y
1   NaN  NaN
2   NaN  NaN
3   NaN  NaN
4   NaN  NaN
5   NaN  NaN
6   NaN  NaN
7   NaN  NaN
8   NaN  NaN
9   NaN  NaN
10  NaN  NaN


Line 16~20에서 For Loop을 통해 값이 저장되면 values는 다음과 같이 변경됩니다:

> values
     x         y
1    1  0.841471
2    2  0.909297
3    3   0.14112
4    4 -0.756802
5    5 -0.958924
6    6 -0.279415
7    7  0.656987
8    8  0.989358
9    9  0.412118
10  10 -0.544021


또 하나의 팁으로써 Line 18과 20에서, iloc은 DataFrame의 행(Row)과 열(Column)의 위치의 값을 불러오거나 저장할 때 유용합니다.

Line 23~36의 코드는 실질적으로 Excel 파일로 저장하는 코드로써 현재 Working Directory에 test.xlsx라는 이름으로 Excel 파일을 저장합니다. 각각에 대한 자세한 옵션은 해당 pandas 문서를 참고하시기 바랍니다.


이렇게 해서 저장된 Excel 파일 test.xlsx을 열면 다음과 같은 형태가 됩니다.


Comments