Reading & writing data

read_csv

read_csv is a function that allows you to read tabular data into a pandas DataFrame.

Examples

How do I read a csv file called grades.csv into a pandas DataFrame?

Solution
import pandas as pd

myDF = pd.read_csv("./grades.csv")
myDF.head()
   grade       year
0    100     junior
1     99  sophomore
2     75  sophomore
3     74  sophomore
4     44     senior

Here, the . represents a relative path to the current directory, or the directory that the program or code was run from. Let’s say we have the following directory tree.

temp
├── grades.csv (1)
└── some_directory
    └── grades.csv (2)

1 directory, 2 files

If we ran the solution inside the temp directory, our code would read in <1>. If we ran the solution inside the some_directory directory, our code would read in <2>.

How do I read a csv file called grades_semi.csv into a pandas DataFrame, where grades_semi.csv is semi-colon-separated instead of comma-separated?

Solution
import pandas as pd

myDF = pd.read_csv("./grades_semi.csv", sep=";")
myDF.head()
   grade       year
0    100     junior
1     99  sophomore
2     75  sophomore
3     74  sophomore
4     44     senior

Resources