ben*_*nsw 3 javascript csv d3.js
我想知道在 D3 或纯 JavaScript 中是否有任何方法可以在我读入数据时即时检查数据类型。
例如,如果我想读“iris.csv”使用d3.csv()做一个箱线图,有没有什么办法来检查sepal_length
,sepal_width
,petal_length
和petal_width
是数值变量,同时species
是一个分类变量?
让我们看看一种可能的解决方案,使用您链接的 CSV:
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3.0,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
etc...
Run Code Online (Sandbox Code Playgroud)
您不能立即执行typeof 操作,因为d3.csv
将所有内容都转换为字符串:
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3.0,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
etc...
Run Code Online (Sandbox Code Playgroud)
d3.csv("https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/d546eaee765268bf2f487608c537c05e22e4b221/iris.csv", function(data) {
var variables = data.columns;
variables.forEach(function(d) {
console.log("typeof " + d + ": " + typeof(data[1][d]))
})
})
Run Code Online (Sandbox Code Playgroud)
但是,我们可以使用isNaN来检查该字符串是否包含数字(警告:使用null
空字符串或将无法正常工作):
<script src="https://d3js.org/d3.v4.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
d3.csv("https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/d546eaee765268bf2f487608c537c05e22e4b221/iris.csv", function(data) {
var variables = data.columns;
variables.forEach(function(d) {
console.log(d + " is: " + (isNaN(data[0][d]) ? "categorical" : "numeric"))
})
})
Run Code Online (Sandbox Code Playgroud)
如您所见,我们只需要data.columns
获取标题,然后,我们只需要第一行值(即data[1]
,不是data[0]
)。实际上,除了第一行 ( data[0]
)之外的任何行都可以使用。
编辑:
你在评论中问:
您对如何处理数据集中的缺失值/空或空字符串有更多的了解吗?
一个简单的方法是检查值是否为假...
!data[index][d]
Run Code Online (Sandbox Code Playgroud)
...然后转到下一行,直到找到合适的值:
var index = 1;
while (data[index][d] === "null" || data[index][d] === "") {
++index;
}
Run Code Online (Sandbox Code Playgroud)
这是演示,我null
在 CSV 中放了一些s 和空字符串,看看:
<script src="https://d3js.org/d3.v4.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
!data[index][d]
Run Code Online (Sandbox Code Playgroud)