How to Export DataFrame to CSV in Julia

You can export your DataFrame to CSV in Julia using this template:

using CSV
CSV.write("Path where your CSV file will be stored\\File Name.csv", df)

Next, I’ll show you the complete steps to apply the above template in practice.

Steps to Export DataFrame to CSV in Julia

Step 1: Install the Relevant Packages

If you have’t already done so, install the DataFrames and CSV packages in Julia.

You can install the DataFrames package using:

using Pkg
Pkg.add("DataFrames")

While you can install the CSV package using:

using Pkg
Pkg.add("CSV")

Step 2: Prepare your dataset

Next, prepare the dataset for your DataFrame.

For illustration purposes, I prepared the following dataset:

Name Age Salary
Jon 22 30000
Bill 43 45000
Maria 81 60000
Julia 52 50000
Mark 27 55000

The goal is to create a DataFrame based on the above data, and then export that DataFrame to CSV.

Step 3: Create a DataFrame

You can now create your DataFrame.

You may use the following code to create the DataFrame for our example:

using DataFrames
df = DataFrame(Name = ["Jon","Bill","Maria","Julia","Mark"], 
               Age = [22,43,81,52,27],
               Salary = [30000,45000,60000,50000,55000]
               )
print(df)

Once you run the code (for example in Jupyter Notebook), you’ll get this DataFrame:

How to Export DataFrame to CSV in Julia

Step 4: Export the DataFrame to CSV in Julia

For the final step, you may use the template below in order to export your DataFrame to CSV in Julia:

using CSV
CSV.write("Path where your CSV file will be stored\\File Name.csv", df)

For our example, the path where the CSV file will be stored on my computer is:

C:\\Users\\Ron\\Desktop\\Test\\export_df.csv

Where ‘export_df‘ is the new file to be created, and ‘.csv‘ is the file extension.

Make sure to use double backslash (‘\\’) in your path name to avoid any errors.

Here is the complete code to export the DataFrame to CSV for our example (you’ll need to modify the path name to reflect the location where the CSV file will be created on your computer):

using CSV
using DataFrames
df = DataFrame(Name = ["Jon","Bill","Maria","Julia","Mark"], 
               Age = [22,43,81,52,27],
               Salary = [30000,45000,60000,50000,55000]
               )

CSV.write("C:\\Users\\Ron\\Desktop\\Test\\export_df.csv", df) 

Run the code (adjusted to your path), and the new CSV file will be created at your specified location.

Once you open the CSV, you’ll see the exported dataset:

Export DataFrame to CSV in Julia