How to Export DataFrame to CSV in Julia

To export a DataFrame to CSV in Julia:

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

Steps to Export DataFrame to CSV in Julia

Step 1: Install the Relevant Packages

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

You can install the DataFrames package using:

using Pkg
Pkg.add("DataFrames")

And 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 example, let’s use the following dataset about products and their prices:

product_idproduct_nameprice
1Oven700
2Refrigerator1200
3Microwave200
4Toaster120
5Dishwasher600

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

Step 3: Create the DataFrame

To create the DataFrame for our example:

using DataFrames

df = DataFrame(product_id = [1, 2, 3, 4, 5],
product_name = ["Oven", "Refrigerator", "Microwave", "Toaster", "Dishwasher"],
price = [700, 1200, 200, 120, 600]
)

print(df)

Step 4: Export the DataFrame to CSV in Julia

For the final step, export the DataFrame to a CSV file using this template:

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

For example, assume that the path where the CSV file will be stored 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:

using CSV
using DataFrames

df = DataFrame(product_id = [1, 2, 3, 4, 5],
product_name = ["Oven", "Refrigerator", "Microwave", "Toaster", "Dishwasher"],
price = [700, 1200, 200, 120, 600]
)

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

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

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

product_idproduct_nameprice
1Oven700
2Refrigerator1200
3Microwave200
4Toaster120
5Dishwasher600

Leave a Comment