[TIP] Pandas를 이용한 CSV 파일 다루기
2022. 4. 23. 23:30
728x90
Pandas는 스프레트시트와 똑같다고 생각하면 좋다. Pandas는 CSV 파일에 내가 원하는 데이터를 작성하거나, 읽어오거나, 수정하는 등의 다양한 작업을 수행할 수 있도록 지원한다.
오늘은 아주 쉽지만, 자주 사용되는 pandas 기본 코드를 살펴본다.
(* 딥러닝에 필요한 CSV 읽기, 쓰기, 혹은 Plot을 위한 header 참조 기반의 데이터 읽어오기만 할 줄 알면 충분하다)
1. CSV 파일 읽기
# === importing ===
import pandas as pd
# read your csv (simple method)
read_csv = pd.read_csv('your_path')
# read your csv (advanced method)
read_csv = pd.read_csv('your_path', idex = 'your_col', squeeze = True)
2. CSV 파일 쓰기 (굉장히 중요, 가령 저장하고자 하는 데이터 셋의 종류가 다르고, 그에 따른 결과도 다른 경우 사용하게 됨)
# === importing ===
import pandas as pd
# write your csv (really useful method)
# this way, dictionary-based writing
# list of series, episodes, actors
series = ['you', 'and' , 'me']
episodes = [1, 2, 3]
actor = ['홍길동', '홍길수', '홍갑수']
# creating your custom dictonary
dict = {'series': series, 'episodes': episodes, 'actors': actors}
# creating data frame
df = pd.DataFrame(dict)
# convert DataFrame to your CSV and writing
df.to_csv('your_custom_dict.csv')
3. header를 이용한 CSV 파일 읽기
# import pandas as pd
# import matplotlib as plt
# import csv
# connect your csv path
get_csv = pd.read_csv('your_csv_path')
# let's consider your csv have some header such as [Times, Scores, Loss]
# header-based read your csv file
header_based_read_csv = get_csv['Scores']
# if you need data length
hedaer_len = list(range(len(header_based_read_csv))
# simple plotting your dataset
plt.figure(1, figsize=(5,5))
plt.plot(header_based_read_csv, '#CA6F1E')
plt.legend(['your dataset name'])
plt.xlabel('your x-axis name',fontsize=10)
plt.ylabel('your y-axis name',fontsize=10)
# you can save any-type such as png, jpg, tif, ttif, pdf.. whatever
# where dip is your display-resoultion
plt.savefig('your_csv_plot_result.png', dpi=600)
plt.show()
728x90
'5G는 공부방 > 기록' 카테고리의 다른 글
[ETC] 우리는 왜 강화학습을 공부해야 하는가? (0) | 2022.04.29 |
---|---|
[TIP] Colab 런타임 유지하는 trick (0) | 2022.04.26 |
[TIP] Python 신뢰 구간 figure 만들기 (0) | 2022.04.23 |
[TIP] MATLAB 코드를 Python으로 변환하는 방법 (0) | 2022.03.14 |
[TIP] Network Attached Storage(NAS) 연결 (0) | 2022.03.12 |