DATA OUTPUT WITH PANDAS:
Pandas provides various functions to export data to different file formats. Here are some common file formats and the corresponding functions in pandas to write data to them:
a. CSV (Comma-Separated Values):
– Use `DataFrame.to_csv()` function to write data to CSV files.
“`python
import pandas as pd
# Write data from a DataFrame to a CSV file
df.to_csv(‘output.csv’, index=False)
“`
b. Excel:
– Use `DataFrame.to_excel()` function to write data to Excel files.
“`python
import pandas as pd
# Write data from a DataFrame to an Excel file
df.to_excel(‘output.xlsx’, index=False)
“`
c. JSON (JavaScript Object Notation):
– Use `DataFrame.to_json()` function to write data to JSON files.
“`python
import pandas as pd
# Write data from a DataFrame to a JSON file
df.to_json(‘output.json’, orient=’records’)
“`
d. SQL (Structured Query Language) Database:
– Use `DataFrame.to_sql()` function to write data to SQL databases.
“`python
import pandas as pd
from sqlalchemy import create_engine
# Create a database connection
engine = create_engine(‘sqlite:///output.db’)
# Write data from a DataFrame to a SQL database
df.to_sql(‘table_name’, engine, if_exists=’replace’, index=False)
“`
e. HTML (HyperText Markup Language):
– Use `DataFrame.to_html()` function to write data to an HTML file.
“`python
import pandas as pd
# Write data from a DataFrame to an HTML file
with open(‘output.html’, ‘w’) as f:
f.write(df.to_html())
“`
These are just a few examples of how to export data to different file formats using pandas. Depending on your requirements, pandas provides a variety of functions to efficiently export your data to various destinations.