如何访问CSV文件的数据元素

How to access a data element of a CSV file?

本文关键字:文件 数据 元素 CSV 何访问 访问      更新时间:2023-09-26

我有一个CSV文件作为数据集。我使用下面的代码来加载它:

var dataset = d3.csv("mydata.csv");

我的问题是如何访问数据集var内的元素。正如我所检查的,数据集变量是一个对象。想象一下,我需要第4行和第7列中的数据元素,我如何获得这段数据?

数据集只在回调函数

中可用
d3.csv("mydata.csv", function(dataset) {
   dataset = data;
   console.log(dataset)
});

d3的这一部分是异步的,这意味着你的javascript代码不会坐在那里等待语句,直到CSV数据加载,因为你可能习惯于从其他语言。相反,你告诉d3一旦数据可用,应该调用什么函数,并从那里开始工作。该函数可以在代码的其他地方定义,或者(更典型地)在d3函数调用中定义。一些例子:

/* Do something with every row */
d3.csv("mydata.csv", function(data) {
  /* Data has been read and is available as an array of 'row' objects */
  data.forEach(function(d) {
    /* Each row has the variable name 'd': 'columns' can be accessed as object properties */
    console.log(+d['Column name']}); //+d ensures conversion to numbers if that is what you need, at first everything is text
  }); //Close the function and .forEach(...) call
}); //Close the function AND the .csv(...) call
/* Just get one value */
d3.csv(csvfile, function(data) {
  /* Read data from row 4 and some column */
  console.log(+data[3]['Column name']}); //As before, but I'm assuming you know the name of column '7'
}); //Close the function AND the .csv(...) call