Exporting to a File
1. Export to CSV
A comma-separated values file is widely used and easy to work with.
# Syntax for exporting to a CSV file
df.to_csv('filename.csv', index=False, sep=',', encoding='utf-8')`
index: Whether to write row indices. Default isTrue.sep: Specifies the separator (default is a comma,).encoding: Sets the file encoding (e.g.,utf-8orlatin1).
2. Export to Excel
For exporting to Excel spreadsheets.
# Syntax for exporting to an Excel file
df.to_excel('filename.xlsx', index=False, sheet_name='Sheet1', engine='openpyxl')`
sheet_name: Name of the sheet to write in the Excel file.engine: The library to use for writing Excel files (e.g.,openpyxlfor.xlsx).
3. Export to JSON
For structured data in JSON format.
# Syntax for exporting to a JSON file
df.to_json('filename.json', orient='records', lines=True)`
orient: Specifies the format of the JSON:'split': Dictionary-like format with columns, index, and data.'records': List of dictionaries.'index': Nested dictionaries with index labels as keys.'columns': Nested dictionaries with columns as keys.
lines: Writes JSON objects line-by-line (useful for streaming).
4. Export to Parquet
For fast, columnar storage with Parquet files.
# Syntax for exporting to a Parquet file
df.to_parquet('filename.parquet', index=False, engine='pyarrow')
engine: The library to use for writing (pyarroworfastparquet).
5. Export to SQL
To write the DataFrame to a database.
df.to_sql('table_name', con=connection_string_to_db, if_exists='replace', index=False)
con: Connection to the database.if_exists: Action if the table exists ('fail','replace', or'append').