Export DataFrame to CSV in Julia

Export DataFrame to CSV in Julia

  • Julia
  • 2 mins read

To export a dataframe to CSV in Julia, you can use the CSV.write() function from the CSV package. Here is an example of how you can use this function to save a dataframe to a CSV file:

Export DataFrame to CSV Examples in Julia

using CSV

# define the dataframe
df = DataFrame(A = [1, 2, 3], B = [4, 5, 6])

# write the dataframe to a CSV file
CSV.write("df.csv", df)

This will save the dataframe to a file named "df.csv" in the current working directory. If you want to specify a different location for the CSV file, you can provide the full file path as the first argument to the CSV.write() function. For example:

CSV.write("/path/to/df.csv", df)

You can also specify additional options to customize the way the data is written to the CSV file. For example, you can specify the delimiter character, the quote character, and whether or not to write the column names as the first row in the CSV file.

Output:

A,B
1,4
2,5
3,6

Here is another example of how you can use the CSV.write() function with some additional options to customize the way the data is written to the CSV file:

using CSV

# define the dataframe
df = DataFrame(A = [1, 2, 3], B = [4, 5, 6])

# write the dataframe to a CSV file with custom options
CSV.write("df.csv", df, delim = ';', quotechar = '"', 
          quotefull = true, writeheader = false)

Output:

1;4
2;5
3;6

In this example, we specify the delimiter character as a comma (;), the quote character as a double quote ("), and set the quotefull option to true to ensure that all fields are quoted. We also set the writeheader option to false to prevent the column names from being written as the first row in the CSV file.

These options can be useful if you want to ensure that the data in the CSV file is formatted in a specific way, or if you need to import the CSV file into another program that expects a certain format.

Related: