Manny
Manny

Reputation: 127

D3js working with unknown: headers/number of columns/number of rows

I am trying to work with CSV files but with unknown header names. How can I refer to each column without knowing the name of the header? Also the number of columns and rows is unknown. What do you think would be the best approach for that?

Upvotes: 2

Views: 2624

Answers (1)

jshanley
jshanley

Reputation: 9128

You could get an array of the header names by calling d3.keys() on the first row of the data returned from d3.csv:

d3.csv('path/to/your/file.csv', function(error, data) {
  var headers = d3.keys(data[0]);
})

Then, depending on what you're trying to do, you could iterate over this array and use each of the header names in turn. For example:

d3.csv('path/to/your/file.csv', function(error, data) {
  var headers = d3.keys(data[0]);
  for (var i = 0; i < headers.length; i++) {
    doSomething(headers[i]);
  }
})

As far as the number of rows, you can find that out simply by getting the length property of the returned data.

d3.csv('path/to/your/file.csv', function(error, data) {
  var numRows = data.length;
})

Jeff K asked if there is a way to guarantee that the order of the keys parsed from the header is the same as was defined in the original file. This is possible, but you need to use the lower-level d3 methods for text parsing.

You can fetch the raw text of the file using d3.text and then parse the rows individually using d3.csv.parseRows. Here is an example:

d3.text('path/to/your/file.csv')
  .get(function(error, rows) {
    var parsedRows = d3.csv.parseRows(rows);
    var headers = parsedRows[0];
  })

The d3.csv.parseRows function creates a two-dimensional Array; an Array of rows, each row being an Array of its values:

[
  [ 'Header1', 'Header2', 'Header3' ],
  [ 329847, 21384, 72912 ],
  [ 232323, 12338, 3218 ],
  ... etc ...
]

By taking the first element in the parsedRows array, you can get back the array of all header values in the order they were defined.

Note: For d3v4 use d3.csvParseRows instead of d3.csv.parseRows

Upvotes: 6

Related Questions