DataFrame.toCSV
Convert DataFrame to a comma-separated values (CSV)
Deprecated in v1.1.0: Use the dfd.toCSV function directly instead
DataFrame.toCSV(options)
Parameters
Type
Description
Default
options
object, optional
Configuration object:
filePath: Local file path to write the CSV file to. If not specified, the CSV will be returned as a string. Only needed in Nodejs version
fileName: The name of the file to download as. Only needed in browser environment.
download: Boolean indicating whether to automatically download the CSV file in the browser. Only needed in the browser environment.
header: Boolean indicating whether to include a header row in the CSV file.
sep: Character to be used as a separator in the CSV file.
{ sep: "," }
The toCSV function can be used to write out a DataFrame or Series to CSV file. The output is configurable and will depend on the environment. In the following examples, we show you how to write/download a CSV file from Node and Browser environments.

Convert DataFrame to CSV string and return value

Node.js
Browser
1
const dfd = require("danfojs-node")
2
3
let data = {
4
Abs: [20.2, 30, 47.3],
5
Count: [34, 4, 5],
6
"country code": ["NG", "FR", "GH"],
7
};
8
9
let df = new dfd.DataFrame(data);
10
11
const csv = df.toCSV();
12
console.log(csv);
13
14
//output
15
Abs,Count,country code
16
20.2,34,NG
17
30,4,FR
18
47.3,5,GH
Copied!
1
<!DOCTYPE html>
2
<html lang="en">
3
4
<head>
5
<meta charset="UTF-8">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/bundle.min.js"></script>
8
<title>Document</title>
9
</head>
10
11
<body>
12
13
<script>
14
15
let data = {
16
Abs: [20.2, 30, 47.3],
17
Count: [34, 4, 5],
18
"country code": ["NG", "FR", "GH"],
19
};
20
21
let df = new dfd.DataFrame(data);
22
23
const csv = df.to_csv({ download: false });
24
console.log(csv);
25
</script>
26
</body>
27
28
</html>
Copied!

Convert DataFrame to CSV and write to local file path

Writing a CSV file to a local file path is only supported in the Nodejs environment
Node.js
1
const dfd = require("danfojs-node")
2
3
let data = {
4
Abs: [20.2, 30, 47.3],
5
Count: [34, 4, 5],
6
"country code": ["NG", "FR", "GH"],
7
};
8
9
let df = new dfd.DataFrame(data);
10
df.toCSV({ filePath: "testOut.csv"});
Copied!

Convert DataFrame to CSV and download file in browser

You can automatically convert and download a CSV file in a browser environment, by specifying a fileName and setting download to true.
1
let data = {
2
Abs: [20.2, 30, 47.3],
3
Count: [34, 4, 5],
4
"country code": ["NG", "FR", "GH"],
5
};
6
7
let df = new dfd.DataFrame(data);
8
9
df.toCSV({ fileName: "testOut.csv", download: true});
Copied!