판다스 (Pandas) (데이터 입출력)

2024. 8. 2. 20:56프로그래밍 (확장)/Python-Pandas

1. CSV 파일 읽기

import pandas as pd

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

 

2. Excel 파일 읽기

import pandas as pd

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

 

3. JSON 파일 읽기

import pandas as pd

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

 

4. HTML 파일 읽기

import pandas as pd

# HTML 파일 읽기
url = 'https://example.com/sample_data.html'
df_list = pd.read_html(url)
df = df_list[0]  # 첫 번째 테이블 선택
print(df)

 

5. SQL 데이터베이스 읽기

import pandas as pd
from sqlalchemy import create_engine

# SQLAlchemy 엔진 생성
engine = create_engine('sqlite:///sample_database.db')

# SQL 쿼리 실행
df = pd.read_sql_query('SELECT * FROM sample_table', engine)
print(df)

 

6. 데이터 저장

 

CSV 파일로 저장:

import pandas as pd

# DataFrame 생성
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# CSV 파일로 저장
df.to_csv('output.csv', index=False)

 

Excel 파일로 저장:

import pandas as pd

# DataFrame 생성
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# Excel 파일로 저장
df.to_excel('output.xlsx', index=False)

 

JSON 파일로 저장:

import pandas as pd

# DataFrame 생성
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# JSON 파일로 저장
df.to_json('output.json', orient='records', lines=True)

 

SQL 데이터베이스로 저장:

import pandas as pd
from sqlalchemy import create_engine

# DataFrame 생성
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# SQLAlchemy 엔진 생성
engine = create_engine('sqlite:///output_database.db')

# SQL 데이터베이스로 저장
df.to_sql('sample_table', engine, if_exists='replace', index=False)

 

 

출처: https://pandas.pydata.org/docs/

 

pandas documentation — pandas 2.2.2 documentation

API reference The reference guide contains a detailed description of the pandas API. The reference describes how the methods work and which parameters can be used. It assumes that you have an understanding of the key concepts.

pandas.pydata.org