现在加载 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:
- If empty, then
null
.- If exactly "true", then
true
.- If exactly "false", then
false
.- If exactly "NaN", then
NaN
.- Otherwise, if coercible to a number, then a number.
- Otherwise, if a date-only or date-time string, then a Date.
- 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/