크롤링보다는 자동화 쪽에 좀 더 관심이 있음.
33. 파이썬 Pandas 사용하기(1) - CSV 읽기, 쓰기
데이터 분석, 데이터 처리
대용량, 정렬, 구조화
- Python Pandas 개요
- CSV 데이터 간단 개요
- 파이썬 Pandas로 CSV 데이터 읽고쓰기
- 파이썬 Pandas로 CSV 데이터 편집하기
과제 : https://support.spatialkey.com/spatialkey-sample-csv-data/ CSV: https://ko.wikipedia.org/wiki/CSV_(파일_형식) Pandas: http://pandas.pydata.org/
CSV
MIME: text/csv
1;2 3,4
4,5,6,7
많은 앱에서 사용 중
1
pip install pandas
csv 파일 읽고 편집
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import pandas as pd
# 기본 읽기
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv')
# print(df)
# 행 스킵
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0])
# print(df)
# 행 스킵, 헤더 생략
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0], header=None)
# print(df)
# 헤더 정의
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0], header=None, names=["Month", 2013, 2014, 2015])
# print(df)
# 인덱스 컬럼 정의
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0], header=None, names=["Month", 2013, 2014, 2015], index_col=[0])
# print(df)
# 특정 값 치환? 잘 안되는 거 같은데?
# df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0], header=None, names=["Month", 2013, 2014, 2015], index_col=[0], na_values=['JAN'])
# print(pd.isnull(df))
# print(df)
# 실습 정리 및 인덱스 재정의
df = pd.read_csv('c:/workspace/section4/csv_s1.csv', skiprows=[0], header=None, names=["Month", 2013, 2014, 2015])
# print(df)
# print(df.index)
# print(list(df.index))
# print(df.index.values)
# print(df.index.values.tolist())
# print(df.rename(index={0: 'aa', 1: 'bb', 2: 'cc'}))
# print(df.rename(index=lambda x: x*10))
# 읽기
df2 = pd.read_csv('c:/workspace/section4/csv_s2.csv', sep=';', skiprows=[0], header=None, names=['Name', 'Test1', 'Test2', 'Test3', 'Final', 'Grade'])
# print(df2)
# 컬럼 내용 변경
# df2['Grade'] = df2['Grade'].str.replace('C', 'A++')
# print(df2['Grade'])
# 평균 컬럼 추가
# df2['Avg'] = df2[['Test1', 'Test2', 'Test3', 'Final']].mean(axis=1)
# print(df2)
# 합계 컬럼 추가
df2['Sum'] = df2[['Test1', 'Test2', 'Test3', 'Final']].sum(axis=1)
print(df2)
csv 쓰기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import pandas as pd
# 읽기
df2 = pd.read_csv('c:/workspace/section4/csv_s2.csv', sep=';', skiprows=[0], header=None, names=['Name', 'Test1', 'Test2', 'Test3', 'Final', 'Grade'])
# print(df2)
# 컬럼 내용 변경
# df2['Grade'] = df2['Grade'].str.replace('C', 'A++')
# print(df2['Grade'])
# 평균 컬럼 추가
df2['Avg'] = df2[['Test1', 'Test2', 'Test3', 'Final']].mean(axis=1)
# print(df2)
# 합계 컬럼 추가
df2['Sum'] = df2[['Test1', 'Test2', 'Test3', 'Final']].sum(axis=1)
print(df2)
# df2.to_csv('c:/workspace/section4/result_s1.csv')
df2.to_csv('c:/workspace/section4/result_s1.csv', index=False)
간단한 샘플
1
2
3
4
5
6
7
8
9
10
import pandas as pd
import numpy as np
# 랜덤으로 DataFrame 생성
# df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=['ONE', 'TWO', 'THREE', 'FOUR'])
df = pd.DataFrame(np.random.randn(100, 4), columns=['ONE', 'TWO', 'THREE', 'FOUR'])
print(df)
# df.to_csv('c:/workspace/section4/result_s2.csv', index=False)
df.to_csv('c:/workspace/section4/result_s2.csv', index=False, header=False)
실습: 샘플 CSV 데이터 다운로드 후 읽기 및 쓰기 실습
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
import urllib.request as req
import os.path
import zipfile
import pandas as pd
# url
url = 'https://support.spatialkey.com/wp-content/uploads/2021/02/FL_insurance_sample.csv.zip'
# 경로, 파일명
savename = 'c:/workspace/section4/sample.csv.zip'
if not os.path.exists(savename):
req.urlretrieve(url, savename)
# 압축 해제
zip_names = []
with zipfile.ZipFile(savename) as my_zip:
zip_names = my_zip.namelist()
my_zip.extractall()
# csv 파일만 필터링
csv_file_names = list(filter(lambda x: not x.startswith('__MACOSX') and x.endswith('.csv'), zip_names))
# print(csv_file_names)
read_file_name = 'c:/workspace/section4/' + csv_file_names[0]
df = pd.read_csv(read_file_name, index_col=[2])
print(df)
df.to_csv('c:/workspace/section4/result_s3.csv')
- 인터넷으로 zip 파일 다운로드 및 압축 해제 후 csv 파일 로드 및 쓰기 완료
- 편집 까지 진행하려고 하다가 해당 csv 데이터가 어떤 데이터인지 까지 파악을 해야 될 것 같아서 간단히 index 정렬까지만 진행하고 완료 함.
34. 파이썬 Pandas 사용하기(2) - Excel 읽기, 쓰기
- 파이썬 Pandas로 엑셀 데이터 읽고 쓰기
- 파이썬 Pandas로 엑셀 데이터 편집하기
- 파이썬 Pandas로 엑셀 데이터 파일 출력
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
핵심
- CSV(Excel) → Pandas로 읽어와 가공(Write)
1
2
pip install xlrd
pip install openpyxl
Excel 읽고 쓰기 (1)
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
import pandas as pd
# xlrd, openpyxl
# 기본 읽기
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx')
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', sheet_name=0)
# print(df)
# print(df.head())
# print(df.tail())
# 행, 푸터(Footer) 스킵
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', skiprows=[0], skipfooter=10)
# print(df)
# 헤더 정의(1)
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', header=0)
# print(df)
# print(list(df))
# print(list(df.columns.values))
# 헤더 정의(2)
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', skiprows=[0], header=None, names=['State', 2003, 2004, 2005])
# print(df)
# 특정 값 치환
# df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', header=0, na_values='...', converters={"2003": lambda w: w if w > 60000 else None})
# print(df)
# print(pd.isnull(df))
# 실습 정리 및 인덱스 재정의
df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', header=0)
# print(df)
print(df.rename(index=lambda x: x+1))
print(df.rename(index=lambda x: x+1).index)
Excel 읽고 쓰기 (2)
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
import pandas as pd
df = pd.read_excel('c:/workspace/section4/excel_s1.xlsx', header=0)
# print(df)
# 컬럼 값 수정
# df['State'] = df['State'].str.replace(' ', '|')
# print(df['State'])
# 평균 컬럼 추가
df['Avg'] = df[['2003', '2004', '2005']].mean(axis=1).round(2)
# print(df)
# 합계 컬럼 추가
df['Sum'] = df[['2003', '2004', '2005']].sum(axis=1).round(2)
# print(df)
# 최대값 출력
print(df[['2003', '2004', '2005']].max(axis=0))
# 최소값 출력
print(df[['2003', '2004', '2005']].min(axis=0))
# 상세 정보
print(df.describe())
df.to_excel('c:/workspace/section4/result_s1.xlsx', index=None)
간단한 샘플
1
2
3
4
5
6
7
8
9
import pandas as pd
import numpy as np
# 랜덤으로 DataFrame 생성
# df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=['ONE', 'TWO', 'THREE', 'FOUR'])
df = pd.DataFrame(np.random.randn(100, 4), columns=['ONE', 'TWO', 'THREE', 'FOUR'])
print(df)
df.to_excel('c:/workspace/section4/result_s2.xlsx', index=False)