Working with CSV Files

This tutorial will show you how to work with CSV (comma-separated values) files in Julia. CSV files are a common, text-based file format that most instrument export data to. All of your lab data will be saved into CSV files. The interface for working with CSV files is part of the CSV package.

You will specifically learn:

  • How to import a CSV file

  • How to save a CSV file

Throughout this exercise we'll work with Anscombe's quartet. This consists of 4 sets of similar X and Y data (here named 1, 2, 3, and 4). These data are available for download from the course website as a CSV file.

8.9 μs

Importing CSV Files

CSV files can be read by Julia and stored in a data frame for further processing.

5.7 μs

Step 1: Load CSV package

You will need the CSV package and the DataFrames package to load a CSV file.

4.9 μs
1.0 s

Step 2: Load the CSV File

Use CSV.read("filename.csv", DataFrame) to load the CSV file.

Here, DataFrame is the sink we wish to store the data in and we are choosing a data frame by typing that.

6.0 μs
anscombe
X_1Y_1X_2Y_2X_3Y_3X_4Y_4
Float64Float64Float64Float64Float64Float64Float64Float64
1
10.0
8.04
10.0
9.14
10.0
7.46
8.0
6.58
2
8.0
6.95
8.0
8.14
8.0
6.77
8.0
5.76
3
13.0
7.58
13.0
8.74
13.0
12.74
8.0
7.71
4
9.0
8.81
9.0
8.77
9.0
7.11
8.0
8.84
5
11.0
8.33
11.0
9.26
11.0
7.81
8.0
8.47
6
14.0
9.96
14.0
8.1
14.0
8.84
8.0
7.04
7
6.0
7.24
6.0
6.13
6.0
6.08
8.0
5.25
8
4.0
4.26
4.0
3.1
4.0
5.39
11.0
12.5
9
12.0
10.84
12.0
9.13
12.0
8.15
8.0
5.56
10
7.0
4.82
7.0
8.26
7.0
6.42
8.0
7.91
11
5.0
5.68
5.0
4.74
5.0
5.73
8.0
6.89
135 μs

The CSV file is now stored as a data frame title anscombe in our Julia workspace. For more on how to work with data frames see the data frames tutorial.

6.3 μs

Exporting (saving) CSV Files

The syntax for writing a CSV file is CSV.write(file, object; ...). The file will be saved in your current working directory unless you specify a different filepath. Existing files will be overwritten without warning!

5.3 μs
525 ms