Pandas를 사용하여 데이터를 읽고 쓰는 방법에 대해 알아보겠습니다.
CSV 파일 읽기
CSV 파일은 pandas에서 가장 일반적으로 사용되는 데이터 형식 중 하나입니다. `read_csv()` 함수를 사용하여 CSV 파일을 DataFrame으로 읽을 수 있습니다:
# python
import pandas as pd
df = pd.read_csv('data.csv')
print(df.to_string())
#
기본적으로 pandas는 처음 5행과 마지막 5행만 출력합니다. 전체 DataFrame을 출력하려면 `to_string()` 메서드를 사용합니다.
Excel 파일 읽기
Excel 파일을 읽으려면 `read_excel()` 함수를 사용합니다:
# python
df = pd.read_excel('sample.xlsx', sheet_name='sheet1')
#
특정 시트를 읽거나 여러 시트를 동시에 읽을 수도 있습니다:
# python
# 인덱스로 시트 지정
df_sheet_index = pd.read_excel('sample.xlsx', sheet_name=1)
# 이름으로 시트 지정
df_sheet_name = pd.read_excel('sample.xlsx', sheet_name='sheet2')
# 여러 시트 읽기
df_sheet_multi = pd.read_excel('sample.xlsx', sheet_name=[0, 'sheet2'])
#
JSON 파일 읽기
JSON 파일은 `read_json()` 함수를 사용하여 읽을 수 있습니다:
# python
df = pd.read_json('data.json')
#
JSON 구조에 따라 `orient` 파라미터를 지정할 수 있습니다.
CSV 파일 쓰기
DataFrame을 CSV 파일로 저장하려면 `to_csv()` 메서드를 사용합니다:
# python
df.to_csv('output.csv', index=False)
#
`index=False`를 사용하면 인덱스를 저장하지 않습니다.
Excel 파일 쓰기
DataFrame을 Excel 파일로 저장하려면 `to_excel()` 메서드를 사용합니다:
# python
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)
#
여러 DataFrame을 하나의 Excel 파일의 다른 시트에 저장하려면 `ExcelWriter`를 사용합니다:
# python
with pd.ExcelWriter('output.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
#
JSON 파일 쓰기
DataFrame을 JSON 파일로 저장하려면 `to_json()` 메서드를 사용합니다:
# python
df.to_json('output.json', orient='records')
#
`orient` 파라미터를 사용하여 JSON 구조를 지정할 수 있습니다.
이러한 방법들을 사용하면 다양한 형식의 파일을 읽고 쓸 수 있어, 데이터 분석 작업을 효율적으로 수행할 수 있습니다.
#파이썬 #Python #데이터분석 #dataanalysis #데이터읽기 #데이터쓰기 #pandas #io #csv #excel #json
0 댓글