Comment on page
danfo.toCSV
Writes a DataFrame or Series to CSV format.
danfo.toCSV(data, options)
Parameters | Type | Description | Default |
data | Series or DataFrame | The Series or DataFrame to write to CSV | |
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.} | {
download: false,
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.
Node.js
Browser
const dfd = require("danfojs-node")
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
const csv = dfd.toCSV(df);
console.log(csv);
//output
Abs,Count,country code
20.2,34,NG
30,4,FR
47.3,5,GH
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/bundle.min.js"></script>
<title>Document</title>
</head>
<body>
<script>
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
const csv = df.toCSV();
console.log(csv);
</script>
</body>
</html>
Writing a CSV file to a local file path is only supported in the Nodejs environment
Node.js
const dfd = require("danfojs-node")
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
dfd.toCSV(df, { filePath: "testOut.csv"});
You can automatically convert and download a CSV file in a browser environment, by specifying a
fileName
and setting download
to true.const dfd = require("danfojs")
let data = {
Abs: [20.2, 30, 47.3],
Count: [34, 4, 5],
"country code": ["NG", "FR", "GH"],
};
let df = new dfd.DataFrame(data);
dfd.toCSV(df, { fileName: "testOut.csv", download: true});
Last modified 1yr ago