Javascript 在 D3 中读取没有标题行的 csv/tsv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13870265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:00:02  来源:igfitidea点击:

read csv/tsv with no header line in D3

javascriptcsvd3.jstsv

提问by by0

I have CSV data which looks something like:

我有 CSV 数据,看起来像:

Data

数据

1,1,10
1,2,50
1,3,5
etc...

And I am trying to read in the data. However, my initial data does not contain a header row (as seen above) so it is taking the first data row to be the header (1,1,10). Is there anyway around this. I want to set the header names after I read the data

我正在尝试读取数据。但是,我的初始数据不包含标题行(如上所示),因此将第一个数据行作为标题 (1,1,10)。有没有办法解决。我想在读取数据后设置标题名称

Javascript

Javascript

d3.csv("data/testnh.csv", function(data) {
    console.log(data);
}

Thanks!

谢谢!

回答by mbostock

Use d3.textto load the data, and then d3.csvParseRowsto parse it. For example:

使用d3.text加载数据,然后使用d3.csvParseRows解析它。例如:

d3.text("data/testnh.csv", function(text) {
  console.log(d3.csvParseRows(text));
});

You'll probably also want to convert your columns to numbers, because they'll be strings by default. Assume they are allnumbers, you could say:

您可能还想将列转换为数字,因为默认情况下它们将是字符串。假设他们是所有的数字,你可以说:

d3.text("data/testnh.csv", function(text) {
  var data = d3.csvParseRows(text).map(function(row) {
    return row.map(function(value) {
      return +value;
    });
  });
  console.log(data);
});

回答by egnha

Since Bostock's answer in 2012, d3.csv.parseRowsallows for an optional accessor function, which enables his answer to be expressed more concisely:

自 2012 年 Bostock 的回答以来,d3.csv.parseRows允许一个可选的访问器函数,这使得他的回答能够更简洁地表达:

d3.text("data/testnh.csv", function(text) {
    var data = d3.csv.parseRows(text, function(d) {
        return d.map(Number);
    });
    // Now do something with data
});

回答by Zhe Hu

first read in data using d3.text, then add custom header string, then parse the result with d3.csv.parse

首先使用 读入数据d3.text,然后添加自定义标头字符串,然后使用d3.csv.parse

d3.text("data/testnh.csv", function(r){
   var result = "x, y, z\n" + r;  //now you have the header
   var data = d3.csv.parse(result);
   //do your plotting with data
}

回答by Bimal Grg

Try d3.csvParse(text)

试试d3.csvParse(text)

d3.csv.parseRows seems doesn't work in modern d3 version.

d3.csv.parseRows 似乎在现代 d3 版本中不起作用。