Module 3 · pandas · Lesson 22 of 66
Reading and writing data
CSV, Excel, HTML tables and SQL databases.
In this lesson · about 14 minutes
- Read and write CSV files
- Read and write Excel files
- Read HTML tables and SQL queries into DataFrames
pandas reads and writes many formats with matching pd.read_… and df.to_… functions. In this course the files live inside your browser's Python, so reading and writing works just like on your own computer.
CSV
Comma-separated text is the most common format. pd.read_csv('example.csv') reads it; df.to_csv('out.csv', index=False) writes it. Pass index=False so the row numbers don't become an extra column.
Excel
pd.read_excel('Excel_Sample.xlsx', sheet_name='Sheet1') reads one sheet. pandas only imports the data, not formulas, charts or images. Writing uses df.to_excel('file.xlsx', sheet_name='Sheet1'). (Older tutorials write sheetname; it's now sheet_name.) Excel support needs the openpyxl package, which loads automatically here the first time.
HTML
pd.read_html(url) finds every <table> on a web page and returns a list of DataFrames. On your computer you can point it at a page address. Browsers block reading other sites directly, so here we pass the HTML as text.
SQL
pandas can write a table into a database and read a query back. Here we use SQLite, a small database that lives in one file (or in memory). For other databases like PostgreSQL you'd connect through SQLAlchemy and a driver, but the pandas calls are the same.
Exercise
Read and total a CSV
Read example.csv into df, then give the sum of column c.
Exercises solved: 0 of 1
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.