Importing and Exporting Files in Python
Real datasets rarely start out as Python code - they usually live in files such as CSV, Excel, or JSON. Pandas provides simple, consistent functions for reading these files into a DataFrame and writing a DataFrame back out.
Reading a CSV File
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head()) # first 5 rows
Reading Excel and JSON Files
df_excel = pd.read_excel("students.xlsx", sheet_name="Sheet1")
df_json = pd.read_json("students.json")
Useful Arguments While Reading
df = pd.read_csv(
"students.csv",
usecols=["Name", "Score"], # only load specific columns
index_col="Name", # use a column as the index
nrows=100 # read only the first 100 rows
)
Exporting a DataFrame
df.to_csv("output.csv", index=False)
df.to_excel("output.xlsx", index=False)
df.to_json("output.json", orient="records")
Coming Up Next
Next, you'll explore the basic functionalities every Pandas data object provides for a first look at your data.