将无标题的CSV导入D3 - 包含数字和字符串的数据 [英] Importing CSV without headers into D3 - data with both numbers and strings
问题描述
我正在开发一个可视化,我需要导入一些csv数据。让我们说csv文件看起来像这样:
I'm working on a visualization where I need to import some csv data. Let's say the csv file looks something like this:
1,4,abc
2,7,def
3,5,ghi
...
csv文件没有头文件,所以做一个搜索我有一些代码看起来像这样:
The csv file does not have a header, so doing a search I have some code that looks like this:
d3.text("data.csv", function(text) {
input = d3.csv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
// do stuff here
});
这对于只包含数字的数据非常有用,但我的数据有数字和字符串。
This works great for data that contains only numbers, but my data has both numbers and strings. How can I modify this code so that only certain columns of data that I choose are turned into numbers?
推荐答案
您可以使用映射
函数中的元素的索引,以查看是否应将其转换为数字:
You can use the index of the element in the map
function to see whether it should be converted to a number:
input = d3.csv.parseRows(text).map(function(row) {
return row.map(function(value, index) {
if(index == 2) {
return value;
} else {
return +value;
}
});
});
这只适用于您的特定情况。
This will only work for your specific case though.
这篇关于将无标题的CSV导入D3 - 包含数字和字符串的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!