This lesson on Reading & Writing Data is hands-on and example-driven. You will be able to seamlessly move data between Pandas DataFrames and common storage formats like CSV, Excel, and JSON. You will learn the standard read_ and to_ methods and how to handle format-specific arguments like separators, index columns, and JSON orientation.
What You'll Be Able To Do
- Read data from a CSV file into a Pandas DataFrame, specifying the index column.
- Export a filtered DataFrame back to a new CSV or tab-delimited file using a custom separator.
- Install necessary Python packages to enable reading and writing of Excel files.
- Write a DataFrame to an XLSX file and read it back, handling sheet names if necessary.
- Control the structure (orientation) of data when writing and reading JSON files.
Detailed Concept Walkthrough
1. CSV and Tab-Delimited Files
CSV (Comma Separated Values) is the most common data exchange format. Pandas uses the same methods for CSV and TSV (Tab Separated Values), differentiating them via the separator argument.
- Mechanism: Use
pd.read_csv()to load data; specify the file path and optionally theindex_colargument to designate a column as the DataFrame index. - Best Practice: When reading or writing TSV, pass
sep='\t'to theread_csv()orto_csv()method to correctly handle the tab delimiter. - Execution Flow: The
df.to_csv()method exports the DataFrame content, including the index (unlessindex=Falseis passed), to the specified file path.
import pandas as pd
# Reading a CSV and setting the index
df = pd.read_csv('data/survey.csv', index_col='Respondent')
# Writing a filtered DataFrame to TSV
india_df.to_csv('data/modified.tsv', sep='\t')
Key Takeaway: CSV and TSV use the same Pandas methods, distinguished only by the
separgument.
2. Handling Excel Files (XLSX)
Excel files (XLS/XLSX) are complex binary formats requiring external Python libraries for interaction. Pandas provides dedicated read_excel and to_excel methods.
- Under the Hood: Writing to newer
.xlsxfiles requires theopenpyxlpackage; writing to older.xlsfiles requiresxlwt. Reading requiresxlrd. These must be installed separately. - Mechanism: Use
df.to_excel('file.xlsx')to export data. The resulting file can contain multiple sheets, which can be specified using thesheet_nameargument. - Best Practice: Always ensure your environment has the necessary I/O packages (
openpyxl,xlwt,xlrd) installed before attempting Excel operations.
# Install required packages (CLI command)
# pip install openpyxl xlwt xlrd
# Writing to XLSX
india_df.to_excel('data/modified.xlsx')
# Reading from XLSX and setting index
test_df = pd.read_excel('data/modified.xlsx', index_col='Respondent')
Key Takeaway: Excel I/O requires specific external libraries and uses dedicated
read_excel/to_excelmethods.
3. JSON Data Structure Orientation
JSON is a text-based format often used for web data exchange. Pandas allows control over how the DataFrame structure maps to the hierarchical JSON format using the orient parameter.
- Mechanism: The default JSON orientation is dictionary-like, where column names are keys and their values are lists of all responses.
- Best Practice: To create a list-like JSON structure (where each line is a complete row/response), use
orient='records'andlines=Truein theto_json()method. - Execution Flow: When reading JSON, the
pd.read_json()method must be passed the sameorientandlinesarguments that were used during writing to correctly reconstruct the DataFrame.
# Writing JSON in a list-like, line-separated format
india_df.to_json('data/modified.json', orient='records', lines=True)
# Reading the list-like JSON back
test_df = pd.read_json('data/modified.json', orient='records', lines=True)
Key Takeaway: Use the
orientparameter into_json()andread_json()to manage the JSON structure.
Topics Covered in Reading & Writing Data
- CSV Read and Write (1:30 - 4:45) — The standard methods
read_csvandto_csvare demonstrated, including setting the index column upon import. - Tab-Delimited Files (4:45 - 6:30) — Tab-delimited files are handled by passing the custom separator
sep='\t'to the standard CSV methods. - Excel Dependencies (6:30 - 9:45) — External packages like
openpyxl,xlwt, andxlrdmust be installed to enable Excel file interaction. - Excel I/O Methods (9:45 - 13:30) — The dedicated methods
to_excelandread_excelare used to export and import data from XLSX files. - Default JSON Export (13:30 - 16:45) — The
to_jsonmethod is introduced, which defaults to a dictionary-like orientation where columns are keys. - JSON Orientation Control (16:45 - 19:30) — Using
orient='records'andlines=Truecreates a list-like JSON structure that is often easier to read and process.
Python Cheat Sheet
-
pd.read_csv(path, index_col='col')— Load data from CSV, set a column as the indexdf = pd.read_csv('data.csv', index_col='ID') -
df.to_csv(path, sep='\t')— Export DataFrame to CSV, specify custom delimiterindia_df.to_csv('out.tsv', sep='\t') -
pip install openpyxl— Install package needed to write newer XLSX filespip install openpyxl xlrd -
df.to_excel(path)— Export DataFrame to the specified Excel file pathindia_df.to_excel('data/out.xlsx') -
pd.read_excel(path, index_col)— Load data from Excel, setting the index columntest_df = pd.read_excel('data.xlsx', index_col='Respondent') -
df.to_json(path, orient='records')— Export DataFrame to JSON, controlling the output structureindia_df.to_json('data.json', orient='records')
Comparison Table
| Format | Read Method | External Dependencies |
|---|---|---|
| CSV/TSV | pd.read_csv() | None |
| Excel (XLSX) | pd.read_excel() | openpyxl, xlrd, xlwt |
| JSON | pd.read_json() | None |
Common Pitfalls
- Mistake: Forgetting to install Excel I/O packages.
Avoid: Run
pip install openpyxl xlrd xlwtbefore using Excel methods. - Mistake: Not specifying the
sep='\t'when reading TSV files. Avoid: Always passsep='\t'toread_csv()for tab-delimited data. - Mistake: Reading a JSON file without matching the
orientused during writing. Avoid: Ensureread_json()arguments match the source file structure. - Mistake: Assuming the DataFrame index is automatically excluded on export.
Avoid: Use
index=Falseinto_csv()orto_excel()if the index is unwanted.
FAQs
- Why do I need to install extra packages for Excel but not CSV?
CSV is a simple text format that Pandas handles natively, but Excel files are complex binary formats requiring specialized libraries like
openpyxlto parse and generate. - How do I read a file that uses a semicolon (;) instead of a comma?
Use the
separgument inpd.read_csv(), setting it to the custom delimiter, e.g.,sep=';'. - What is the difference between the default JSON orientation and
orient='records'? Default (dictionary-like) groups data by column;orient='records'groups data by row, making it list-like and often easier for line-by-line processing.