【问题标题】:How to access a data element of a CSV file?如何访问 CSV 文件的数据元素?
【发布时间】:2014-07-07 03:29:17
【问题描述】:

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

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

我的问题是如何访问数据集 var 中的元素。正如我所检查的,数据集变量是一个对象。想象一下,我需要第 4 行第 7 列的数据元素,我怎样才能得到那条数据?

【问题讨论】:

  • 它应该是一个数组对象,如文档中提到的[ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"}, {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ]

标签: javascript csv d3.js


【解决方案1】:

数据集仅在回调函数中可用

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

试试这样的。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多