How to Import a CSV File with Python using pandas
In this short tutorial, you will read a CSV file using Python and pandas.
TLDR solution
import pandas as pd
df = pd.read_csv("path-to-file/file-name.csv")
Step-by-Step Example
Step 1: Install the pandas Package
If you don't have pandas already installed, execute the following command in your terminal:
pip install pandas
Step 2: Have a CSV File Ready
Let's say, you have a CSV saved on your desktop with the following content:
Fish,Size_inch,Size_cm
salmon,30,76
pufferfish,4,10
shark,60,152
Step 3: Create a Python Script
Let's create a Python script that imports the CSV file on your desktop and prints its content to your terminal:
import os
import pandas as pd
desktop_path = os.path.expanduser("~/Desktop")
df = pd.read_csv(desktop_path + "/fish_size.csv")
print(df)
Create a new file using a text editor of your choice, copy-paste the above Python code into it, and save it as import_csv.py on your desktop.
Verify that it works by navigating your terminal to your desktop and running the script:
cd Desktop
python import_csv.py
You should see the following output in your terminal:
Fish Size_inch Size_cm
0 salmon 30 76
1 pufferfish 4 10
2 shark 60 152
Optional Step: Select a Subset of Columns
Sometimes you only want to read a subset of columns of CSV file, e.g., when it is large.
In that case, add the usecols option to your script:
import os
import pandas as pd
desktop_path = os.path.expanduser("~/Desktop")
df = pd.read_csv(desktop_path + "/fish_size.csv",
usecols=['Fish', 'Size_cm'])
print(df)
The output of the adjusted script is as follows:
Fish Size_cm
0 salmon 76
1 pufferfish 10
2 shark 152
That's it! You just learned how to import a CSV file with Python and pandas.