파이썬을 이용하다보면, 현재 불러온 데이터를 정제하여 다른 데이터 형식이나 확장자로 저장할 일이 있습니다. 이때 바로바로 사용할 수 있는 메서드들이 있습니다. to_로 시작하는 메서드들은 to_뒤에 무엇을 쓰느냐에 따라 원하는 모양으로 변경할 수 있습니다.
to_string
- to_string(): 데이터프레임을 문자열로 변환하여 출력합니다. 주로 표 형태로 출력하는데 사용됩니다.- index와- header매개변수를 사용하여 인덱스와 헤더를 출력 여부를 설정할 수 있습니다.- index: 기본값은- True이며, 인덱스를 출력할지 여부를 설정합니다.
- header: 기본값은- True이며, 열 이름을 출력할지 여부를 설정합니다.
 
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# to_string() 메서드를 사용하여 데이터프레임을 문자열로 변환
string_output = df.to_string(index=False, header=False)  # 인덱스와 열 이름을 출력하지 않음
print("=== Output ===")
print(string_output)=== Output ===
 Alice   25  New York
   Bob   30     Paris
Charlie  35    London
  David   40     Tokyoto_csv
- to_csv(): 데이터프레임을 CSV 파일로 저장합니다.- path_or_buf: CSV 파일의 경로 또는 파일 객체를 지정합니다.
- sep: 기본값은- ,이며, 필드를 구분하는 구분자를 설정합니다.
- na_rep: 기본값은 빈 문자열(- '')이며, 결측값을 대체할 문자열을 설정합니다.
- index: 기본값은- True이며, 인덱스를 포함할지 여부를 설정합니다.
 
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# to_csv() 메서드를 사용하여 데이터프레임을 CSV 파일로 저장
df.to_csv('output.csv', sep='|', index=False)
print("=== Output ===")
print("CSV file 'output.csv' has been saved.")=== Output ===
CSV file 'output.csv' has been saved.to_excel
- to_excel(): 데이터프레임을 Excel 파일로 저장합니다.- excel_writer: Excel 파일의 경로 또는 파일 객체를 지정합니다.
- sheet_name: Excel 파일에 생성될 시트의 이름을 설정합니다.
- na_rep: 기본값은 빈 문자열(- '')이며, 결측값을 대체할 문자열을 설정합니다.
- index: 기본값은- True이며, 인덱스를 포함할지 여부를 설정합니다.
 
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# to_excel() 메서드를 사용하여 데이터프레임을 Excel 파일로 저장
df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)
print("=== Output ===")
print("Excel file 'output.xlsx' has been saved.")=== Output ===
Excel file 'output.xlsx' has been saved.
to_html
- to_html(): 데이터프레임을 HTML 형식으로 변환하여 출력합니다.- buf: HTML 문자열을 저장할 변수나 파일 객체를 지정합니다.
- index: 기본값은- True이며, 인덱스를 출력할지 여부를 설정합니다.
- border: 기본값은- 1이며, 테이블의 테두리 두께를 설정합니다.
 
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# to_html() 메서드를 사용하여 데이터프레임을 HTML 형식으로 변환
html_output = df.to_html(index=False)
print("=== Output ===")
print(html_output)
=== Output ===
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>Name</th>
      <th>Age</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Alice</td>
      <td>25</td>
      <td>New York</td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>30</td>
      <td>Paris</td>
    </tr>
    <tr>
      <td>Charlie</td>
      <td>35</td>
      <td>London</td>
    </tr>
    <tr>
      <td>David</td>
      <td>40</td>
      <td>Tokyo</td>
    </tr>
  </tbody>
</table>
to_dict
- to_dict(): 데이터프레임을 딕셔너리로 변환합니다.- orient: 기본값은- 'dict'이며, 딕셔너리 형식으로 변환할 방식을 설정합니다.- 'dict',- 'list',- 'series',- 'split',- 'records'중 하나를 선택할 수 있습니다.
 
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# to_dict() 메서드를 사용하여 데이터프레임을 딕셔너리로 변환
dict_output = df.to_dict(orient='records')  # records 형식으로 변환
print("=== Output ===")
print(dict_output)=== Output ===
[{'Name': 'Alice', 'Age': 25, 'City': 'New York'}, {'Name': 'Bob', 'Age': 30, 'City': 'Paris'}, {'Name': 'Charlie', 'Age': 35, 'City': 'London'}, {'Name': 'David', 'Age': 40, 'City': 'Tokyo'}]to_json
- to_json(): 데이터프레임을 JSON 형식으로 변환합니다.- path_or_buf: JSON 파일의 경로 또는 파일 객체를 지정합니다.
- orient: 기본값은- 'columns'이며, JSON 형식으로 변환할 방식을 설정합니다.- 'columns',- 'index',- 'records',- 'split'중 하나를 선택할 수 있습니다.
 
import json
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
json_data = json.dumps(data)
print(json_data){"name": "John", "age": 30, "city": "New York"}
to_markdown
- to_markdown(): 데이터프레임을 Markdown 형식으로 변환하여 출력합니다.- index: 기본값은- True이며, 인덱스를 출력할지 여부를 설정합니다.
- tablefmt: Markdown 표 형식을 설정합니다.- 'pipe',- 'simple',- 'github',- 'grid'등이 있습니다.
 
def to_markdown(data):
    markdown = ""
    for key, value in data.items():
        markdown += f"| {key} | {value} |\n"
    
    return markdown
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
markdown_data = to_markdown(data)
print(markdown_data)
| name | John |
| age | 30 |
| city | New York |to_clipboard
- to_clipboard(): 데이터프레임을 클립보드에 복사합니다.- excel: 기본값은- True이며, 클립보드에 데이터를 복사할 때 Excel 형식으로 복사할지 여부를 설정합니다.
 
import pyperclip
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
pyperclip.copy(str(data))(클립보드에 복사됨)to_sql
- to_sql(): 데이터프레임을 SQL 데이터베이스에 저장합니다.- name: 저장할 테이블의 이름을 설정합니다.
- con: 데이터베이스 연결 객체를 지정합니다.
- if_exists: 기본값은- 'fail'이며, 동일한 이름의 테이블이 이미 존재할 경우의 동작 방식을 설정합니다.- 'fail',- 'replace',- 'append'중 하나를 선택할 수 있습니다.
- index: 기본값은- True이며, 인덱스를 포함할지 여부를 설정합니다.
 
import sqlite3
def to_sql(data, table_name):
    conn = sqlite3.connect('data.db')
    cursor = conn.cursor()
    
    create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, city TEXT);"
    cursor.execute(create_table_query)
    
    insert_data_query = f"INSERT INTO {table_name} (name, age, city) VALUES (?, ?, ?);"
    cursor.execute(insert_data_query, (data['name'], data['age'], data['city']))
    
    conn.commit()
    conn.close()
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
to_sql(data, 'person')
(SQLite 데이터베이스에 데이터가 저장됨)