javascript - 如何将多个d3.csv数据转换为数字?

标签 javascript d3.js

现在加载 csv 文件后,我正在循环数组中的每个对象并一一转换。

看起来像

fulldata.forEach(function(data){
      data.healthcare = +data.healthcare;
      data.a = +data.a;
      data.b = +data.b;
      data.c = +data.c;
    })

假设您需要将大约 100 个特征转换为数字,有没有一种方法可以将多个特征一次性转换为数字?

最佳答案

D3 v5引入了一个非常方便的方法,叫做d3.autoType ,其中:

For each value in the given object, the trimmed value is computed; the value is then re-assigned as follows:

  1. If empty, then null.
  2. If exactly "true", then true.
  3. If exactly "false", then false.
  4. If exactly "NaN", then NaN.
  5. Otherwise, if coercible to a number, then a number.
  6. Otherwise, if a date-only or date-time string, then a Date.
  7. Otherwise, a string (the original untrimmed value).

当您没有所有列作为数值时,这非常方便。例如,使用d3.csvParse,您只需要:

const fullData = d3.csvParse("your_CSV_URL_here", d3.autoType);

这是一个演示:

const csv = `number,string,date
32,foo,2019-01-21
47,bar,2018-11-19
17,baz,2019-07-28`;

const data = d3.csvParse(csv, d3.autoType);

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.0/d3.min.js"></script>

但是,如果实际上您有所有列作为数值,只需获取row函数内的所有属性即可:

const csv = `foo,bar,baz
12,43,23
75,44,32
76,93,23`;

const data = d3.csvParse(csv, function(d) {
  d3.keys(d).forEach(function(e) {
    d[e] = +d[e]
  })
  return d;
});

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - 如何将多个d3.csv数据转换为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56319066/

相关文章:

javascript - 如何使用 HTML 表单和 Javascript 更新 JSON 文件?

javascript - 使用c3 js,有没有办法在放大时显示更多的x轴值?

javascript - 是否可以捕获 JavaScript 中的属性访问?

javascript - 创建一个具有可变属性高度的半圆形饼图

Javascript D3 直方图 : thresholds producing wrong number of bins

javascript - D3js高亮栏一一连续

javascript - 在服务中无法访问 Angular ngResource 响应对象

javascript - jQuery 移动版 : force jquery mobile initialization?

text - 截断 d3 中的文本

formatting - d3.js:tickformat - 添加一个 % 符号而不乘以 100