AI/데이터 분석과 모델 학습

5. 데이터 전처리의 모든 것 : DataFrame 파일 입출력

코코도롱 2024. 4. 18. 16:25
반응형

1. 파일 입출력


Pandas는 다양한 형식의 파일을 읽고, 쓸 수 있습니다. 대표적인 파일 형식으로는 CSV, Excel, JSON, SQL 등이 있습니다.

(Pandas 공식 User Guide 2.2 기준)

Format Type Data 형태 불러오는 함수 (읽기) 내보내기 함수 (쓰기)
text CSV read_csv to_csv
text Fixed-Width Text File read_fwf  
text JSON read_json to_json
text HTML read_html to_html
text LaTeX   Styler.to_latex
text XML read_xml to_xml
text Local clipboard read_clipboard to_clipboard
binary MS Excel read_excel to_excel
binary OpenDocument read_excel  
binary HDF5 Format read_hdf to_hdf
binary Feather Format read_feather to_feather
binary Parquet Format read_parquet to_parquet
binary ORC Format read_orc to_orc
binary Stata read_stata to_stata
binary SAS read_sas  
binary SPSS read_spss  
binary Python Pickle Format read_pickle to_pickle
SQL SQL read_sql to_sql
SQL Google BigQuery read_gbq to_gbq

 

[파일 읽기 / 불러오기]


CSV 파일 읽기 / 불러오기

# CSV 파일 읽기
df = pd.read_csv('file.csv')

 

Excel  파일 읽기 / 불러오기

# Excel 파일 읽기
df = pd.read_excel('file.xlsx')

 

Json 파일 읽기 / 불러오기

# JSON 파일 읽기
df = pd.read_json('file.json')

 

[파일 쓰기 / 내보내기]

 

CSV 파일 쓰기 / 내보내기

# 예제 DataFrame 생성
data = {'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']}
df = pd.DataFrame(data)

# CSV 파일로 저장
df.to_csv('output.csv', index=False)  # index를 False로 설정하여 인덱스를 저장하지 않음

 

Excel 파일 쓰기 / 내보내기

 

# 예제 DataFrame 생성
data = {'A': [1, 2, 3],
        'B': ['a', 'b', 'c']}

df = pd.DataFrame(data)

# Excel 파일로 저장
df.to_excel('example.xlsx', index=False)  # index=False를 설정하여 인덱스를 저장하지 않습니다.

 

 

Json 파일 쓰기 / 내보내기

# 예제 DataFrame 생성
data = {'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']}
df = pd.DataFrame(data)

# JSON 파일로 저장
df.to_json('output.json', orient='records')  # orient를 'records'로 설정하여 레코드 단위로 저장
반응형